PHP String Replacement: Complete Guide
In PHP, you can replace strings by using either the str_replace function or the preg_replace function.
- replace string
- replace the string
$str = "Hello World!";
$new_str = str_replace("World", "PHP", $str);
echo $new_str; // 输出:Hello PHP!
- replace the content with the specified content
- replace the specified pattern with a new value
$str = "The quick brown fox jumps over the lazy dog";
$new_str = preg_replace("/brown/", "red", $str);
echo $new_str; // 输出:The quick red fox jumps over the lazy dog
The choice between the two methods for replacing strings depends on specific needs and circumstances.