Loading... # PHP字符串常用函数 1. strlen():获取字符串的长度。 ``` $string = "Hello, world!"; $length = strlen($string); echo $length; // 输出:13 ``` 2. strpos():查找字符串中第一次出现某个子串的位置。 ``` $string = "Hello, world!"; $pos = strpos($string, "world"); echo $pos; // 输出:7 ``` 3. substr():获取字符串的一个子串。 ``` $string = "Hello, world!"; $sub = substr($string, 0, 5); echo $sub; // 输出:Hello ``` 4. str_replace():替换字符串中的某些子串。 ``` $string = "Hello, world!"; $new_string = str_replace("world", "PHP", $string); echo $new_string; // 输出:Hello, PHP! ``` 5. strtoupper():将字符串转换为大写字母。 ``` $string = "Hello, world!"; $upper = strtoupper($string); echo $upper; // 输出:HELLO, WORLD! ``` 6. strtolower():将字符串转换为小写字母。 ``` $string = "Hello, world!"; $lower = strtolower($string); echo $lower; // 输出:hello, world! ``` 7. trim():删除字符串两端的空格。 ``` $string = " Hello, world! "; $trimmed = trim($string); echo $trimmed; // 输出:Hello, world! ``` 8. htmlspecialchars():将字符串中的特殊字符转换为HTML实体。 ``` $string = "<script>alert('Hello');</script>"; $html = htmlspecialchars($string); echo $html; // 输出:<script>alert('Hello');</script> ``` 9. explode():使用一个分隔符将一个字符串分割成一个数组。 ``` $string = "apple,banana,orange"; $array = explode(",", $string); print_r($array); // 输出:Array ( [0] => apple [1] => banana [2] => orange ) ``` 10. implode():将一个数组元素连接成一个字符串,并使用指定的分隔符分隔它们。 ``` $array = array("apple", "banana", "orange"); $string = implode(",", $array); echo $string; // 输出:apple,banana,orange ``` 11. ucfirst():将字符串的首字母转换为大写。 ``` $string = "hello, world!"; $ucfirst = ucfirst($string); echo $ucfirst; // 输出:Hello, world! ``` 12. ucwords():将字符串中每个单词的首字母转换为大写。 ``` $string = "hello, world!"; $ucwords = ucwords($string); echo $ucwords; // 输出:Hello, World! ``` 13. strrev():将字符串反转。 ``` $string = "Hello, world!"; $reversed = strrev($string); echo $reversed; // 输出:!dlrow ,olleH ``` 14. sprintf():将格式化的字符串写入一个变量中。 ``` $number = 10; $string = sprintf("The number is %d", $number); echo $string; // 输出:The number is 10 ``` 15. addslashes():在字符串中添加反斜杠转义特殊字符。 ``` $string = "It's a beautiful day!"; $escaped = addslashes($string); echo $escaped; // 输出:It\'s a beautiful day! ``` 猜你想看 每日一学:PHP 中的array_fill函数详解 Vue生命周期 今天吃什么-解决选择困难症 Golang 中 printf 占位符详解 go使用DialTimeout实现TCP端口扫描 vue组件数据共享 每日一学:PHP 中的array_search函数详解 TS自动运行+Parcel打包 使用 linux go-cqhttp搭建QQ机器人 关于设计API接口 最后修改:2023 年 02 月 21 日 © 允许规范转载 赞 0 如果觉得我的文章对你有用,请随意赞赏