PHP’s str_replace function will replace every occurrence of the selected string with another string.

echo str_replace("car", "bike", "That car is red!");

The code above displays the text: That bike is red!
Function parameters:

str_replace(searched_string, replacement_string, target_string, count)

searched_string – the string that will be replaced
replacement_string – the string that will be used to replace the searched string
target_string – the string in which the replacement will occur
count – the number or replacements that will be performed, if it is not specified all of the occurrences will be replaced

Notes:

  • The count parameter has been added in PHP5
  • The function is binary safe
  • The function is case-sensitive (use str_ireplace() function for case insensitive replace)
  • The function replaces from left to right

You can use arrays in replacements too:

Case 1: replace all values from an array with a single value

$arr = array('orange', 'lemon', 'pear');
str_replace($arr, 'apple', 'orange is big, lemon is small, pear is good');

It will return: apple is big, apple is small, apple is good

Case 2: replace all values from an array with another values from another array

$arr = array('orange', 'lemon', 'pear');
$arr2 = array('Hulk', 'Alvin', 'Pizza');
str_replace($arr, $arr2, 'orange is big, lemon is small, pear is good');

It will return: Hulk is big, Alvin is small, Pizza is good

LaunchTAE14