PHP字符串替换函数:10个最常用的字符串替换函数实例解析
1. str_replace()
str_replace() 函数用于将一个字符串中的所有指定字符或字符串替换为新的字符或字符串,它的语法如下:
str_replace(search, replace, subject)
其中,search 表示需要被替换的字符或字符串,replace 表示用来替换的新字符或字符串,subject 表示需要进行替换操作的字符串。
示例:
$str = "Hello World!";
$new_str = str_replace("World", "PHP", $str);
echo $new_str; // 输出结果为:Hello PHP!
2. substr_replace()
substr_replace() 函数用于将字符串中指定位置的一段子串替换为新的字符或字符串,它的语法如下:
substr_replace(string, replacement, start, length)
其中,string 表示需要进行替换的字符串,replacement 表示用来替换的新字符或字符串,start 表示要进行替换的子串的起始位置,length 表示要替换的子串的长度。
示例:
$str = "Hello World!";
$new_str = substr_replace($str, "PHP", 6, 5);
echo $new_str; // 输出结果为:Hello PHP!
3. str_ireplace()
str_ireplace() 函数与 str_replace() 函数类似,只不过它是忽略大小写的。它的语法如下:
str_ireplace(search, replace, subject)
示例:
$str = "Hello World!";
$new_str = str_ireplace("world", "PHP", $str);
echo $new_str; // 输出结果为:Hello PHP!
4. preg_replace()
preg_replace() 函数可以通过正则表达式进行字符串替换。它的语法如下:
preg_replace(pattern, replacement, subject)
其中,pattern 表示需要匹配的正则表达式,replacement 表示用来替换的新字符或字符串,subject 表示需要进行替换操作的字符串。
示例:
$str = "Hello World!";
$new_str = preg_replace("/World/i", "PHP", $str);
echo $new_str; // 输出结果为:Hello PHP!
5. preg_replace_callback()
preg_replace_callback() 函数也是进行正则表达式替换的函数,不同的是它使用一个回调函数来处理替换的结果。它的语法如下:
preg_replace_callback(pattern, callback, subject)
其中,pattern、subject 意义同 preg_replace() 函数,callback 表示要进行处理替换结果的回调函数,该函数必须返回一个替换的字符串。
示例:
$str = "Hello World!";
$new_str = preg_replace_callback("/World/i", function($matches){return "PHP";}, $str);
echo $new_str; // 输出结果为:Hello PHP!
6. strtr()
strtr() 函数用于将一个字符串中指定的字符或字符串替换为新的字符或字符串。它的语法如下:
strtr(string, from, to)
其中,string 表示需要进行替换的字符串,from 表示需要被替换的字符或字符串,to 表示用于替换的新字符或字符串。
示例:
$str = "Hello World!";
$new_str = strtr($str, "W", "P");
echo $new_str; // 输出结果为:Hello Porl!
7. substr()
substr() 函数用于获取字符串中指定位置的一段子串,可以用它来进行替换操作。它的语法如下:
substr(string, start, length)
其中,string 表示需要进行处理的字符串,start 表示要获取子串的起始位置,length 表示要获取的子串的长度。
示例:
$str = "Hello World!";
$new_str = substr($str, 6, 5);
echo $new_str; // 输出结果为:World
8. mb_substr()
mb_substr() 函数也是获取字符串中指定位置的一段子串的函数,不同的是它可以处理多字节字符。它的语法如下:
mb_substr(string, start, length, encoding)
其中,encoding 表示要使用的字符编码。
示例:
$str = "Hello World!中文";
$new_str = mb_substr($str, 6, 5, "UTF-8");
echo $new_str; // 输出结果为:World
9. str_pad()
str_pad() 函数用于在字符串的左侧或右侧补充指定字符以达到指定的长度。它的语法如下:
str_pad(string, length, pad_string, pad_type)
其中,string 表示需要进行处理的字符串,length 表示要达到的长度,pad_string 表示要填充的字符或字符串,pad_type 表示填充的位置(LEFT、RIGHT、BOTH)。
示例:
$str = "Hello";
$new_str = str_pad($str, 10, "*", STR_PAD_RIGHT);
echo $new_str; // 输出结果为:Hello*****
10. rtrim()
rtrim() 函数用于去掉字符串右侧的空格或指定字符。它的语法如下:
rtrim(string, charlist)
其中,string 表示需要进行处理的字符串,charlist 表示需要去掉的字符。
示例:
$str = " Hello ";
$new_str = rtrim($str);
echo $new_str; // 输出结果为: Hello
以上是 PHP 中最常用的 10 个字符串替换函数,可以根据具体需求选择适合的替换方法。
