str_replace()
The PHP str_replace() function replaces all occurrences of a search string with a replacement string. It is useful for finding and substituting specific patterns within larger text. Below, we cover the syntax, key features, and usage examples.
The str_replace() function is used to replace all occurrences of a string within another string. The syntax of the str_replace() function is as follows:
The PHP syntax of the str_replace()
str_replace($search, $replace, $subject, $count = null)The function takes three required parameters and one optional parameter: $search, $replace, $subject, and $count.
$search: The string or array of strings to search for.$replace: The string or array of strings to replace with.$subject: The string or array of strings to search within.$count(optional): If provided, this variable is filled with the number of replacements made.
Here is an example of how to use the str_replace() function:
Example of PHP str_replace()
<?php
$string = "The quick brown fox jumps over the lazy dog.";
$new_string = str_replace("brown", "red", $string);
echo $new_string; // Output: The quick red fox jumps over the lazy dog.
?>In this example, we have a string variable $string that contains the phrase "The quick brown fox jumps over the lazy dog." We use the str_replace() function to replace the word "brown" with the word "red" by specifying the $search parameter as "brown" and the $replace parameter as "red".
The output of this code will be:
The quick red fox jumps over the lazy dog.As you can see, the str_replace() function has successfully replaced the word "brown" with the word "red" in the original string.
The function also supports arrays for $search and $replace, and can track the number of replacements using the $count parameter:
Example with arrays and $count
<?php
$search = ["brown", "fox"];
$replace = ["red", "bear"];
$subject = "The quick brown fox jumps over the lazy dog.";
$count = 0;
$result = str_replace($search, $replace, $subject, $count);
echo $result; // Output: The quick red bear jumps over the lazy dog.
echo "Replacements made: $count"; // Output: Replacements made: 2
?>The str_replace() function provides a straightforward way to search and replace strings or arrays of strings in PHP. Mastering it will help you write more efficient text-processing code.
Practice
What does str_replace function do in PHP?