PHP String Replace Tutorial

There are several methods available in PHP to search for and replace strings.

  1. Using the str_replace() function:
    This function can search for specified content in a string and then replace it with new content.
    Syntax: str_replace(content to search for, content to replace with, original string)
  2. Sample code:
  3. The code replaces the word “World” with “PHP” in the string “Hello, World!” and then outputs the new string as “Hello, PHP!”
  4. Use the preg_replace() function: This function allows you to use regular expressions to match content in a string and replace it with new content. Syntax: preg_replace(regular expression, content to replace, original string)
  5. Example Code:
  6. $str = “Hello, World!”;
    $newStr = preg_replace(“/\bWorld\b/”, “PHP”, $str);
    echo $newStr; // Output: Hello, PHP!
  7. Using the strtr() function:
    This function can replace characters in a string based on a specified character mapping table.
    Syntax: strtr(original string, character mapping table to replace)
  8. Example code:
  9. $str = “Hello, World!”;
    $map = array(“World” => “PHP”);
    $newStr = str_replace(array_keys($map), array_values($map), $str);
    echo $newStr; // Output: Hello, PHP!

All of the methods mentioned can achieve searching and replacing in strings, the specific method chosen depends on your needs and the characteristics of the string.

bannerAds