PHP Tutorial > String Functions > str_replace Function
The str_replace function in PHP is used to change certain occurrances on a string with a replacement string. The syntax of the str_replace function is:
str_replace ('match_pattern', 'replacement_pattern', 'text', [count])
The parameter match_pattern is the match to look for. replacement_pattern is the replacement string to use. Both match_pattern and replacement_pattern can be of several data types (not limited to strings). text is the initial string. The optional parameter count is used to count the number of matches to replace.
Let's take a look at the examples below:
print str_replace ('str','k','The string replacement function in PHP is str_replace');
The king replacement function in PHP is k_replace
$match_pattern = array("junior", "senior");
$replacement_pattern = array("freshmen","sophmore");
$starting_text = "This senior is studying PHP.";
print str_replace ($match_pattern, $replacement_pattern, ,$starting_text);
This sophmore is studying PHP.
The word "senior" is the second element in the match array, which is replaced by the word "sophmore", which is the second element in the replacement array.
Next: PHP strlen Function