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
相关推荐
Kalika0-040 分钟前
猴子吃桃-C语言
c语言·开发语言·数据结构·算法
_.Switch42 分钟前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
代码雕刻家1 小时前
课设实验-数据结构-单链表-文教文化用品品牌
c语言·开发语言·数据结构
一个闪现必杀技1 小时前
Python入门--函数
开发语言·python·青少年编程·pycharm
Fan_web1 小时前
jQuery——事件委托
开发语言·前端·javascript·css·jquery
龙图:会赢的1 小时前
[C语言]--编译和链接
c语言·开发语言
小鹿( ﹡ˆoˆ﹡ )1 小时前
探索IP协议的神秘面纱:Python中的网络通信
python·tcp/ip·php
XKSYA(小巢校长)3 小时前
NatGo我的世界联机篇
开发语言·php
Cons.W3 小时前
Codeforces Round 975 (Div. 1) C. Tree Pruning
c语言·开发语言·剪枝
憧憬成为原神糕手3 小时前
c++_ 多态
开发语言·c++