PHP String str_replace() Function
The PHP String str_replace() function is used to replace all occurrences of the search string or array of search strings with a replacement string or array of replacement strings in the given string or array, respectively.
Syntax
Below is the syntax of the PHP String str_replace() function −
string|array str_replace( array|string $search, array|string $replace, string|array $subject, int &$count = null )
Parameters
Here are the parameters of the str_replace() function −
$search − (Required) It is the value that is wanted, also known as the needle. An array can be used to represent many needles.
$replace − (Required) It is the value that replaces the found search results. An array can be used to provide several replacements.
$subject − (Required) It specifies the string to be searched.
$count − (Optional) It is a variable for counting the number of replacements.
Return Value
The str_replace() function returns a string or an array having all occurrences of the search term in the subject replaced with the replace value specified.
PHP Version
First introduced in core PHP 4, the str_replace() function continues to function easily in PHP 5, PHP 7, and PHP 8.
Example 1
Here is the basic example of the PHP String str_replace() function to replace a single word in a string.
<?php
$text = "I love apples.";
$result = str_replace("apples", "bananas", $text);
echo $result;
?>
Output
Here is the outcome of the following code −
I love bananas.
Example 2
In the below PHP code we will use the str_replace() function and replace multiple words in a string with the help of an arrays for search and replace.
<?php $text = "Roses are red, violets are blue."; $search = ["red", "blue"]; $replace = ["green", "yellow"]; $result = str_replace($search, $replace, $text); echo $result; ?>
Output
This will generate the below output −
Roses are green, violets are yellow.
Example 3
Now the below code uses str_replace() function to count how many replacements were made at the time of the process.
<?php $text = "I see the sea, the sea is blue."; $search = "sea"; $replace = "ocean"; $count = 0; $result = str_replace($search, $replace, $text, $count); echo $result; echo "\nReplacements made: " . $count; ?>
Output
This will create the below output −
I see the ocean, the ocean is blue. Replacements made: 2
Example 4
In the following example, we are using the str_replace() function to replace values within an array of strings.
<?php $textArray = ["I love apples.", "Apples are sweet.", "Apples keep the doctor away."]; $search = "apples"; $replace = "bananas"; $result = str_replace($search, $replace, $textArray); print_r($result); ?>
Output
Following is the output of the above code −
Array ( [0] => I love bananas. [1] => Bananas are sweet. [2] => Bananas keep the doctor away. )