10个常用的PHP字符串函数详解
发布时间:2023-06-09 13:52:49
1. strlen()
该函数用于获取字符串的长度,它只能用于单字节字符集。
$str = "hello world"; echo strlen($str); // 输出 11
2. strpos()
该函数用于查找字符串中第一个匹配的子串,如果没找到返回 false。
$str = "hello world"; $pos = strpos($str, "world"); echo $pos; // 输出 6
3. substr()
该函数用于获取字符串的子串,第一个参数是原始字符串,第二个参数是起始位置,第三个参数是子串长度。
$str = "hello world"; $sub = substr($str, 0, 5); echo $sub; // 输出 hello
4. str_replace()
该函数用于替换字符串中所有匹配的子串,第一个参数是要替换的子串,第二个参数是替换后的字符串,第三个参数是原始字符串。
$str = "hello world";
$newstr = str_replace("world", "php", $str);
echo $newstr; // 输出 hello php
5. strtolower()
该函数用于把字符串转化为小写字母。
$str = "Hello World"; $newstr = strtolower($str); echo $newstr; // 输出 hello world
6. strtoupper()
该函数用于把字符串转化为大写字母。
$str = "Hello World"; $newstr = strtoupper($str); echo $newstr; // 输出 HELLO WORLD
7. trim()
该函数用于去掉字符串两端的空格或指定字符。
$str = " hello world "; $newstr = trim($str); echo $newstr; // 输出 hello world
8. explode()
该函数用于把字符串按照指定分隔符分成数组。
$str = "hello,world";
$arr = explode(",", $str);
print_r($arr); // 输出 Array ( [0] => hello [1] => world )
9. implode()
该函数用于把数组元素按照指定分隔符连接成字符串。
$arr = array("hello", "world");
$str = implode(",", $arr);
echo $str; // 输出 hello,world
10. sprintf()
该函数用于格式化字符串。
$num = 5;
$str = sprintf("There are %d apples", $num);
echo $str; // 输出 There are 5 apples
上述是常用的10个PHP字符串函数的详解,掌握它们将使我们在字符串处理方面更加娴熟,能够更加高效地开发代码。
