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
相关推荐
再见晴天*_*8 分钟前
SpringBoot 中单独一个类中运行main方法报错:找不到或无法加载主类
java·开发语言·intellij idea
lqjun08272 小时前
Qt程序单独运行报错问题
开发语言·qt
亿坊电商3 小时前
物联网领域中PHP框架的最佳选择有哪些?
物联网·struts·php
hdsoft_huge3 小时前
Java & Spring Boot常见异常全解析:原因、危害、处理与防范
java·开发语言·spring boot
wuzuyu3654 小时前
用php做一个简易的路由
php·路由
风中的微尘4 小时前
39.网络流入门
开发语言·网络·c++·算法
未来之窗软件服务4 小时前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
小冯记录编程5 小时前
C++指针陷阱:高效背后的致命危险
开发语言·c++·visual studio
1uther5 小时前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎
C_Liu_5 小时前
C++:类和对象(下)
开发语言·c++