PHP str_replace() Function

What is PHP str_replace() Function?

If you want to replace all the occurrences of a sub string in a string by another sub string, use str_replace() function. Example, replacing “SOW” by “Schools of Web”, we can convert “Learn web development at SOW.” to “Learn web development at Schools of Web”. Not only in one string, this function facilitates us to make the replacement in multiple strings at a time if we use array instead of a string.

Syntax:

str_replace(search, replace, subject, count)

Parameters:

The Function has 3 required parameters and 1 optional parameter-

search (Required): It can be both array or string. It is the value to be searched. It is also known as needle.

replace (Required): It can be both array or string. It is the value to be replaced by the “search” value.

subject (Required): It can be both array or string. It is where the search and replace take place. It is also known as haystack.count (Optional): It is a variable where the function stores the number of replacement takes place. Check example 5.

The table below shows what the str_replace() function outputs when the “search” and “replace” parameters are either strings or arrays. You can read the “string” as single and “array” as multiple. For example, you can read the 3rd row as “For multiple search and single replacement, the function returns-”.

search”“replace”Output
StringStringReturns a string. It replaces all the occurrences of the “search” string with the “replace” string. Check example 1.
StringArrayTypeError. “replace” must be a string, when “search” is an array. Check example 2.
ArrayStringReturns a string if the “subject” is a string. Else returns an array if the “subject” is an array. It replaces occurrences of each element in the “search” array with the “replace” string. Check example 3.
ArrayArrayReturns an array. The function takes each element from both arrays serially one by one and replace them on the “subject”. Check example 4.

Return Values:

This function returns an array or a string with the replaced value.

Examples:

Example 1: When both the “search” and the “replace” are strings-

<?php
echo str_replace("a","1", "abac a");
?>

Output:

1b1c 1

Explanation:

The function takes the “search” (“a”) and replace any “a” it finds in the subject string (third parameter) with the replace para,eter (“1”).

Example 2: When the “search” is a string and the “replace” is an array-

<pre>
<?php
print_r( str_replace("abc",["1","2","3"], "abc")) . "<br />";
print_r( str_replace("abc",["1","2","3"], ["abc","b","c"]));

?>
</pre>

Output:

Fatal error:  Uncaught TypeError: str_replace(): Argument #2 ($replace) must be of type string when argument #1 ($search) is a string in D:\xampp\htdocs\str_replace.php:3

Stack trace:

#0 D:\xampp\htdocs\str_replace.php(8): str_replace(‘abc’, Array, ‘abc’)

#1 {main}  

thrown in D:\xampp\htdocs\str_replace.php on line 3

Explanation:

“replace” (second parameter) must be a string when the “search” (first parameter) is a string. That’s why, the function throws a TypeError.

Example 3: When the “search” is an array and the “replace” is a string –

<pre>
<?php
echo str_replace(["a","b"],"1","abc") . "<br />";
print_r(str_replace(["a","b"],"1",["a","b","c"]));
?>
</pre>

Output:

11c1
Array
(
    [0] => 1
    [1] => 1
    [2] => c
    [3] => 1
)

Explanation:

Line 3: The function takes the first element(“a”) of the “search” array and replaces all its matches it finds in the subject string “abca” with the “replace” string (“1”).

Line 4: Same process happens here, except in place of string, array is used as subject.

Example 4: When both the “search” and the “replace” are arrays –

<pre>
<?php
echo str_replace(["a","b","c"],["1","2","3"], "abc") . "<br />";
print_r(str_replace(["a","b"],["1","2"],["a","b","c","a"]));
print_r(str_replace(["a","b","c"],["1","2"],["a","b","c"]));
?>
</pre>

Output:

123
Array
(
    [0] => 1
    [1] => 2
    [2] => c
    [3] => 1
)
Array
(
    [0] => 1
    [1] => 2
    [2] =>
)

Explanation:

Line 3: The function replaces the character of the subject string (third parameter) by the “replace” elements (first array) matching with the corresponding “search” elements (second array).

Line 4: The function takes first element(“a” & “1”) from “search” (first array) and “replace” (second array) arrays and replaces “a” with any “1” finds in the subject array (third array). After that, it takes the second element “b” and the process continues.

Example 5: Calculating replacement number with the 4th parameter, count –

<?php
echo str_replace(["a", "b"],"1", "abac a", $count) . "<br />";
echo $count;
?>

Output:

111c 1
4

Explanation:

The function replaced 4 elements – three “a” and one “b”.

Example 6: When one search term is part of another search term-

<?php
echo str_replace(["C","C++"],"PHP","C++ is a popular language.") . "<br />";
echo str_replace(["C++","C"],"PHP","C++ is a popular language.");
?>

Output:

PHP++ is a popular language.
PHP is a popular language.

Explanation:

The first search element “C” is part of the second search element “C++”. And note the second search element is in the beginning of the string. The function takes the first search element “C” which is the part of the second search element and finds a partial match with “C++” in the third parameter and replaces it with “PHP” and creates “PHP++”. If you don’t want to replace “C++” by “PHP”, place “C++” before “C” in the search array (line 3).

Example 7: str_replace() function performs case sensitive search –

<?php
echo str_replace("A","1", "abac") . "<br />";
echo str_replace("a","1", "abac");
?>

Output:

abac
1b1c

Example 8: str_replace() function doesn’t modify the actual string –

<?php
$string = "Check PHP courses.";
$modified_string = str_replace("PHP","our", $string) . "<br />";
echo "Old string: " . $string . "<br />" . "Modified string: " . $modified_string;
?>

Output:

Old string: Check PHP courses.
Modified string: Check our courses.

Explanation:

After modifying the actual string, you can save it in a new variable (line 3). But, you can update the actual string with the modified one (line 5).

Example 9: str_replace() function considers position not index of “search” and “replacement” arrays-

<pre>
<?php
print_r(str_replace(array(0=>"a",1=>"b"),array(0=>"1",1=>"2"),["a","b"]));
print_r(str_replace(array(0=>"a",1=>"b"),array(1=>"1",0=>"2"),["a","b"]));
print_r(str_replace(array(1=>"a",0=>"b"),array(0=>"1",1=>"2"),["a","b"]));
?>
</pre>

Output:

Array
(
    [0] => 1
    [1] => 2
)
Array
(    
   [0] => 1    
   [1] => 2
)
Array
(    
   [0] => 1    
   [1] => 2
)

Explanation:

The values of the “search”, “replace”, and “subject” of all the three str_replace() functions are all same according to the position. And the outputs of the all three functions are same. Though, first two functions have different index numbers of “search” and “replace” and the third one has different index number of “subject” string. So, index number doesn’t affect the replacement process, the replacement depends on the position of the values.

Example 10: str_replace() function performs a binary-safe operation –

<?php
echo str_replace("A","B", "\x41B");
?>

Output:

BB

Explanation:

“\x41” is hexadecimal character “B”. The function can recognize this, and performs accordingly.

Example 11: What happens when “search” array contains more element than “replace” array does –

<?php
echo str_replace(["a","b","c"],["1","2"], "abc") . "<br />";
?>

Output:

12

Explanation:

As there is no corresponding “replace” parameter for the “search” element “c”, the function replaces “c” by an empty string which convert the string “abc” to “12”. But, you may expect the new string as “12c”

Example 12: When one replacement could be the another search term-

<?php
echo str_replace(["a","b","c"],["b","c","d"], "abc");
?>

Output:

ddd

Explanation:

For the first letter “a” of the string “abc”, at first “a” is replaced by “b”, then “b” is replaced by “c”, then then “c” is replaced by “d”. Same replacements happen for the next two letters.

Practical Usages of str_replace() Function:

You can use this function in many situations, few includes-

  • Often in a word document (like MS word), we search a word in a long document and replace all its occurrence with another word. We can accomplish this with this function.
  • When you send the same email to a lots of recipients you usually just change the recipient name, company name, sender name etc. In this case, str_replace() is a very helpful function. Have a look at the code below-
    <?php
    $string = “Hello #recipient#\n I would like to formally introduce myself. My name is #sender# and I am from #company#........”;
    $email = str_replace([‘#recipient#’, ‘#sender#’ , ‘#company#’],[‘David’, ‘John’, ‘Schools of Web’], $string);
    ?>
    
  • As a part of creating slug of an URL, you can use str_replace() function. The following code generates the slug “php-string-functions”.
    <?php
    $string = “php string functions”;
    str_replace(“ ”, “-”, $string);
    ?>
    

Best practices of str_replace() Function:

If one search term is part of another search term, then place the most specific search term before the general term, in the other word, place the longer term at first. Check example 6.

Notes on str_replace() Function:

  • The function performs a case sensitive search and replacement. It differentiates lowercase and uppercase characters. So, the function can’t replace “a” in the string with “A”. Check example 7.
  • The function doesn’t modify the actual string or array; it just returns a modified string/array with the replacements. But, if you want to modify the original string, put the output of the function to this string.  Check example 8.
  • If “search” or “replace” is an array, its elements are processed serially from left to right during the replacement. Even, if the “subject” is an array, the function replaces its elements from left to right also. Check any example.
  • If both “search” and “replace” are arrays, the function takes elements from each array and replaces on the subject. When the function takes elements from each array, it doesn’t consider element’s index number, it considers position in the array. Check example 9.
  • This is a binary-safe function. So, it can handle any UTF-8 encoded text or any binary data. Check example 10.

Caution:

  • You know that if both “search” and “replace” are arrays, and “search” has more elements than “replace”, then, the function replaces an empty string for each short “replace” value. It could be an unintentional replacement which could create error. Check example 11.
  • Be careful when one replacement could be the search term of the subsequent search element. Check example 12.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP str_replace() Function

str_replace() function is a very powerful and useful function to accomplish case sensitive search and replacement. It is another most used built-in string function. If used properly, it will make your development work easy.

Reference:

https://www.php.net/manual/en/function.str-replace.php