牛牛在线工具

str_replace()

收录 8868 个 PHP 函数,含用途说明与用法示例。

str_replace()

替换字符串中的部分内容

函数名:str_replace() 适用版本:所有PHP版本(PHP 4,PHP 5,PHP 7) 用法:替换字符串中的部分内容 语法: str_replace($search, $replace, $subject, $count) 参数: $search(必需):要查找的字符串或字符串数组。 $replace(必需):用于替换的字符串或字符串数组。 $subject(必需):要在其中进行替换的字符串或字符串数组。 $count(可选):替换的次数。默认为全部替换。 返回值:替换后的字符串或字符串数组。 示例1: $str = "Hello, World!"; $newStr = str_replace("World", "PHP", $str); echo $newStr; // 输出:Hello, PHP! 示例2: $search = array("blue", "red", "green"); $replace = array("yellow", "purple", "orange"); $str = "The sky is blue, the rose is red, and the grass is green."; $newStr = str_replace($search, $replace, $str); echo $newStr; // 输出:The sky is yellow, the rose is purple, and the grass is orange. 示例3: $search = array("apple", "banana", "orange"); $replace = "fruit"; $str = "I like apple, banana, and orange."; $newStr = str_replace($search, $replace, $str, $count); echo $newStr; // 输出:I like fruit, fruit, and fruit. echo $count; // 输出:3 注意事项: 如果$search和$replace都是数组,那么$str也必须是数组,函数将对每个元素进行替换。 如果$search和$replace都是字符串,那么$str也必须是字符串,函数将只替换第一个匹配项。 $count参数是可选的,如果提供了该参数,将返回替换的次数。 str_replace()函数是区分大小写的,如果需要进行不区分大小写的替换,可以使用str_ireplace()函数。