常用的10个PHP字符串处理函数
1. strlen
strlen函数用于获取一个字符串的长度,返回值为整数类型。如:
$str = "hello world";
echo strlen($str); //输出11
2. strpos
strpos函数用于在一个字符串中查找另一个字符串的位置,返回值为整数类型。如:
$str = "hello world";
echo strpos($str, "world"); //输出6
3. substr
substr函数用于截取字符串的一部分,返回截取的子串。如:
$str = "hello world";
echo substr($str, 0, 5); //输出hello
4. str_replace
str_replace函数用于替换一个字符串中的另一个字符串。如:
$str = "hello world";
echo str_replace("world", "php", $str); //输出hello php
5. strtolower
strtolower函数用于将一个字符串中的大写字母转化为小写字母。如:
$str = "HELLO WORLD";
echo strtolower($str); //输出hello world
6. strtoupper
strtoupper函数用于将一个字符串中的小写字母转化为大写字母。如:
$str = "hello world";
echo strtoupper($str); //输出HELLO WORLD
7. trim
trim函数用于去除一个字符串中的空格或者其他特定的字符。如:
$str = " hello world ";
echo trim($str); //输出hello world
8. explode
explode函数用于将一个字符串按照指定的分隔符拆分成一个数组。如:
$str = "hello,world,php";
print_r(explode(",", $str)); //输出Array ( [0] => hello [1] => world [2] => php )
9. implode
implode函数用于将一个数组连接成一个字符串,可以指定连接符。如:
$arr = array("hello", "world", "php");
echo implode(" ", $arr); //输出hello world php
10. htmlspecialchars
htmlspecialchars函数用于将字符串中的特殊字符转义,避免在HTML中出现问题。如:
$str = "<script>alert('hello');</script>";
echo htmlspecialchars($str); //输出<script>alert('hello');</script>
