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
相关推荐
Predestination王瀞潞4 小时前
IO操作(Num22)
开发语言·c++
宋恩淇要努力5 小时前
C++继承
开发语言·c++
沿着路走到底6 小时前
python 基础
开发语言·python
沐知全栈开发7 小时前
C# 委托(Delegate)
开发语言
任子菲阳7 小时前
学Java第三十四天-----抽象类和抽象方法
java·开发语言
csbysj20208 小时前
如何使用 XML Schema
开发语言
R6bandito_8 小时前
STM32中printf的重定向详解
开发语言·经验分享·stm32·单片机·嵌入式硬件·mcu
earthzhang20218 小时前
【1007】计算(a+b)×c的值
c语言·开发语言·数据结构·算法·青少年编程
杨枝甘露小码8 小时前
Python学习之基础篇
开发语言·python
武文斌779 小时前
项目学习总结:LVGL图形参数动态变化、开发板的GDB调试、sqlite3移植、MQTT协议、心跳包
linux·开发语言·网络·arm开发·数据库·嵌入式硬件·学习