The str_replace() function is used to replace some case-sensitive characters in a string. This function was introduced in PHP3. The str_replace() function replaces parts of a string with new parts you specify and takes a minimum of three parameters: what to look for, what to replace it with, and the string to work with. If you provide it, it also has an optional fourth parameter, which will be filled with the number of replacements made.
Syntax:
str_replace( array|string $search, array|string $replace, string|array $subject, int &$count = null ): string|array
Use the str_replace() function to perform a simple string replacement. Here’s how to replace summer with winter in a string taken.
$string = "It's summer season!"; print(str_replace("summer", "winter", $string));
Notice that str_replace() does not replace the substring in the original string. If you’d like to do that, reassign it to the original string:
$string = str_replace("summer", "winter", $string);
Other methods of replacing characters in a string:
str_replace() strtr()
Parameters
Parameter | Description |
search | The value being searched for, otherwise known as the needle. |
replace | The replacement value that replaces found search values. |
subject | The string or array being searched and replaced on, otherwise known as the haystack. |
count | If passed, this will be set to the number of replacements performed. |
Return Values
This function returns a string or an array with the replaced values.
Examples
Example 1:
<?php $replace = array("a", "e"); $aft_replace = str_replace($replace, "i", "We are learning php"); echo $aft_replace."
"; $team = "Sourav, Rahul,Anil all are great cricketers."; echo $team."
"; $present = array("Sourav", "Rahul","Anil"); $future = array("Dhoni", "Rohit", "Sehbag"); $newteam = str_replace($present, $future, $team,$num); echo $newteam."
"; echo "there are {$num} change in team"; ?>
The output of the above program is as follows:
Wi iri liirning php Sourav, Rahul, Anil all are great cricketers. Dhoni, Rohit, Sehwag all are great cricketers. there are 3 change in team
Example 2:
To replace only the first n occurrences of a substring, add the number as a fourth parameter (this is especially handy for replacing just the first occurrence):
str_replace("summer", "winter", $string, n);
Example 3:
To delete all occurrences of a substring, just use an empty string as the replace argument:
$string = str_replace("summer", "", $string);