PHP关于字符串的各类处理方法

判断字符串是否以指定子串开头或结尾

php 复制代码
function startsWith($str, $prefix) {
    return stripos($str, $prefix) === 0;
}

function endsWith($str, $suffix) {
    return substr_compare($str, $suffix, -strlen($suffix)) === 0;
}

// 示例用法
$text = "hello world";
$result = startsWith($text, "he");
echo $result;  // 输出结果: true

$text = "hello world";
$result = endsWith($text, "ld");
echo $result;  // 输出结果: true

统计字符串中指定子串出现的次数

php 复制代码
function countSubstring($str, $substring) {
    return substr_count($str, $substring);
}

// 示例用法
$text = "Hello, hello world!";
$result = countSubstring($text, "hello");
echo $result;  // 输出结果: 2

检查字符串是否为空或只包含空白字符

php 复制代码
function isStringEmpty($str) {
    return trim($str) === "";
}

// 示例用法
$text = "  ";
$result = isStringEmpty($text);
echo $result;  // 输出结果: true

格式化字符串为驼峰命名法

php 复制代码
function toCamelCase($str) {
    $str = ucwords(str_replace(['-', '_'], ' ', $str));
    return lcfirst(str_replace(' ', '', $str));
}

// 示例用法
$text = "hello-world";
$result = toCamelCase($text);
echo $result;  // 输出结果: helloWorld

检查字符串是否是回文

php 复制代码
function isPalindrome($str) {
    $str = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $str));
    return $str === strrev($str);
}

// 示例用法
$text = 'A man, a plan, a canal: Panama.';
$result = isPalindrome($text);
echo $result ? '是回文' : '不是回文';  // 输出结果: 是回文

提取字符串中的数字

php 复制代码
function extractNumbers($str) {
    preg_match_all('/\d+/', $str, $matches);
    return implode('', $matches[0]);
}

// 示例用法
$text = 'abc123def456';
$result = extractNumbers($text);
echo $result;  // 输出结果: 123456

翻转字符串中的单词顺序

php 复制代码
function reverseWords($str) {
    return implode(' ', array_reverse(explode(' ', $str)));
}

// 示例用法
$text = 'Hello world, this is PHP.';
$result = reverseWords($text);
echo $result;  // 输出结果: PHP. is this world, Hello

删除字符串中的空格

php 复制代码
function removeSpaces($str) {
    return str_replace(' ', '', $str);
}

// 示例用法
$text = 'Hello, World!';
$result = removeSpaces($text);
echo $result;  // 输出结果: Hello,World!

替换字符串中的特定内容

php 复制代码
function replaceString($str, $search, $replace) {
    return str_replace($search, $replace, $str);
}

// 示例用法
$text = "hello world";
$result = replaceString($text, "world", "everyone");
echo $result;  // 输出结果: hello everyone
相关推荐
belldeep3 小时前
如何阅读、学习 Tcc (Tiny C Compiler) 源代码?如何解析 Tcc 源代码?
c语言·开发语言
LuckyTHP3 小时前
java 使用zxing生成条形码(可自定义文字位置、边框样式)
java·开发语言·python
Blossom.1186 小时前
使用Python实现简单的人工智能聊天机器人
开发语言·人工智能·python·低代码·数据挖掘·机器人·云计算
da-peng-song6 小时前
ArcGIS Desktop使用入门(二)常用工具条——数据框工具(旋转视图)
开发语言·javascript·arcgis
galaxy_strive6 小时前
qtc++ qdebug日志生成
开发语言·c++·qt
TNTLWT6 小时前
Qt功能区:简介与安装
开发语言·qt
等等5437 小时前
Java EE初阶——wait 和 notify
java·开发语言
低代码布道师7 小时前
第五部分:第一节 - Node.js 简介与环境:让 JavaScript 走进厨房
开发语言·javascript·node.js
盛夏绽放7 小时前
Python字符串常用方法详解
开发语言·python·c#
好吃的肘子8 小时前
Elasticsearch架构原理
开发语言·算法·elasticsearch·架构·jenkins