PHP String Replace Tutorial
There are several methods available in PHP to search for and replace strings.
- 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) - Sample code:
- The code replaces the word “World” with “PHP” in the string “Hello, World!” and then outputs the new string as “Hello, PHP!”
- 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)
- Example Code:
- $str = “Hello, World!”;
$newStr = preg_replace(“/\bWorld\b/”, “PHP”, $str);
echo $newStr; // Output: Hello, PHP! - 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) - Example code:
- $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.