PHP String Replacement: Complete Guide

In PHP, you can replace strings by using either the str_replace function or the preg_replace function.

  1. replace string
  2. replace the string
$str = "Hello World!";
$new_str = str_replace("World", "PHP", $str);
echo $new_str; // 输出:Hello PHP!
  1. replace the content with the specified content
  2. 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.

bannerAds