欢迎访问宙启技术站
智能推送

PHP中常见字符串函数

发布时间:2023-06-20 07:27:23

PHP中常见的字符串函数很多,在这里列出了常用的一些函数,并对它们进行简单的介绍。

一、字符串拼接

1. .$str1.$str2:将两个字符串拼接起来,返回一个新的字符串。

示例代码:

$str1 = "hello";

$str2 = "world";

$newstr = $str1.$str2;

echo $newstr;

输出结果为:helloworld

二、字符串截取

2. substr($str,$start,$length):用于截取字符串,$str为原始字符串,$start表示起始位置,$length表示要截取的长度。返回截取后的字符串。

示例代码:

$str = "abcdefg";

$newstr = substr($str,0,3);

echo $newstr;

输出结果为:abc

3. mb_substr($str,$start,$length):与substr函数类似,但是可处理多字节字符集中的字符串。

三、字符串替换

4. str_replace($search,$replace,$str):用$replace替换$str中的$search,返回新的字符串。

示例代码:

$str = "hello world";

$newstr = str_replace("world","php",$str);

echo $newstr;

输出结果为:hello php

四、字符串查找

5. strpos($str,$search):查找$search在$str中 次出现的位置,返回 次出现位置的索引值。如果没找到,返回false。

示例代码:

$str = "hello world";

$pos = strpos($str,"world");

echo $pos;

输出结果为:6

6. stripos($str,$search):与strpos函数类似,但是不区分大小写。

7. strstr($str,$search):查找$search在$str中 次出现的位置,返回一个从 个出现位置到字符串结尾的子字符串。如果没找到,返回false。

示例代码:

$str = "hello world";

$newstr = strstr($str,"world");

echo $newstr;

输出结果为:world

8. stristr($str,$search):与strstr函数类似,但是不区分大小写。

五、字符串去除空格

9. trim($str):去除字符串的首尾空格。

示例代码:

$str = " hello ";

$newstr = trim($str);

echo $newstr;

输出结果为:hello

10. ltrim($str):仅去除字符串的左侧空格。

11. rtrim($str):仅去除字符串的右侧空格。

六、字符串大小写转换

12. strtolower($str):将字符串转化为小写字母。

示例代码:

$str = "Hello World";

$newstr = strtolower($str);

echo $newstr;

输出结果为:hello world

13. strtoupper($str):将字符串转化为大写字母。

七、字符串分割

14. explode($delimiter,$str):将字符串按照$delimiter分割为数组,返回一个数组。

示例代码:

$str = "a,b,c,d,e";

$arr = explode(",",$str);

print_r($arr);

输出结果为:Array ( [0] => a [1] => b [2] => c [3] => d [4] => e )

15. implode($delimiter,$arr):与explode函数相反,将数组按照$delimiter连接为一个字符串。

八、字符串长度

16. strlen($str):返回字符串的长度。

示例代码:

$str = "hello world";

$length = strlen($str);

echo $length;

输出结果为:11

以上就是PHP中常见的字符串函数。相信掌握了这些常用函数之后,会对字符串的操作更加得心应手。