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
相关推荐
NEU-UUN2 分钟前
C语言 . 第三章第二节 .递归函数
c语言·开发语言
weixin_307779139 分钟前
Python编码规范之字符串规范修复程序详解
开发语言·python·代码规范
郝学胜-神的一滴17 分钟前
深入理解 Python 的 __init_subclass__ 方法:自定义类行为的新方式 (Effective Python 第48条)
开发语言·python·程序人生·个人开发
普普通通的南瓜1 小时前
《国家安全法》下的 SSL 证书定位:网络数据加密的 “法定基石”
网络·php·ssl
初见无风1 小时前
3.0 Lua代码中的闭包
开发语言·lua·lua5.4
Eiceblue1 小时前
使用 Python 向 PDF 添加附件与附件注释
linux·开发语言·vscode·python·pdf
loong_XL1 小时前
AC自动机算法-字符串搜索算法:敏感词检测
开发语言·算法·c#
xrkhy2 小时前
Java全栈面试题及答案汇总(2)
java·开发语言
@LetsTGBot搜索引擎机器人2 小时前
从零打造 Telegram 中文生态:界面汉化 + 中文Bot + @letstgbot 搜索引擎整合实战
开发语言·python·搜索引擎·github·全文检索
洲覆2 小时前
缓存异常:缓存穿透、缓存击穿、缓存雪崩
开发语言·数据库·mysql·缓存