PHP str_ireplace() Function

What is PHP str_ireplace() 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.

But, I hear that you’re looking for case-sensitive search? Then, you better use str_replace() function. It is case-sensitive version of str_ireplace() function.

Syntax:

str_ireplace(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_ireplace() function outputs when the “search” and “replace” parameters are either strings or arrays. You can read the “String” as single and “Array” as multiple. So, 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_ireplace("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 parameter (“1”). As it is a case insensitive function, it replaces “a” by “A”.

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

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

Output:

Fatal error:  Uncaught TypeError: str_ireplace(): Argument #2 ($replace) must be of type string when argument #1 ($search) is a string in D:\xampp\htdocs\str_ireplace.php:3
Stack trace:
#0 D:\xampp\htdocs\phpExercise\281. str_ireplace function.php(3): str_ireplace(‘aBc’, Array, ‘abc’)
#1 {main}   thrown in D:\xampp\htdocs\str_ireplace.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_ireplace(["A","B"],"1","abca") . "<br />";
print_r(str_ireplace(["a","B"],"1",["a","b","c", "a"]));
?>
</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 the letter “A” in case insensitive manner 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_ireplace(["A","B","C"],["1","2","3"], "abc") . "<br />";
print_r(str_ireplace(["A","B"],["1","2"],["a","b","c", "a"]));
print_r(str_ireplace(["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) in a case insensitive manner.

Line 4: The function takes first elements (“A” & “1”) from “search” (first array) and “replace” (second array) arrays and replaces “1” with any “A” finds in the subject array (third array) in a case insensitive manner. 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_ireplace(["A", "b"],"1", "abac a", $count) . "<br />";
echo "Replacement occurred: ". $count;
?>

Output:

111c 1
Replacement occurred: 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_ireplace(["C","c++"],"PHP","c++ is a popular language.") . "<br />";
echo str_ireplace(["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++” if you overlook the case. 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_ireplace() function doesn’t modify the actual string –

<?php
$string = "Check PHP courses.";
$modified_string = str_ireplace("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 8: str_replace() function considers position not index number of “search” and “replacement” arrays-

<pre>
<?php
print_r(str_ireplace(array(0=>"A",1=>"b"),array(0=>"1",1=>"2"),["a","b"]));
print_r(str_ireplace(array(0=>"A",1=>"b"),array(1=>"1",0=>"2"),["a","b"]));
print_r(str_ireplace(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_ireplace() 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 9: str_replace() function performs a binary-safe operation –

<?php
echo str_ireplace("A","B", "B\x61");
?>

Output:

BB

Explanation:

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

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

<?php
echo str_ireplace(["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 11: When one replacement could be the another search term-

<?php
echo str_ireplace(["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. Note the function performs case-insensitive search and replacement here.

Practical Usages of str_ireplace() Function:

  • 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. Note, the replacement occurs in case-insensitive manner.
  • 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_ireplace() 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_ireplace([‘#recipient#’, ‘#sender#’ , ‘#company#’],[‘David’, ‘John’, ‘Schools of Web’], $string);
    ?>
    
  • As a part of creating slug of an URL, you can use str_ireplace() function. The following code generates the slug “php-string-functions”.
    <?php
    $string = “php string functions”;
    str_ireplace(“ ”, “-”, $string);
    ?>
    

Best practices of str_ireplace() 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_ireplace() Function:

  • 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 7.
  • If the “search” or the “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 8.
  • This is a binary-safe function. So, it can handle any UTF-8 encoded text or any binary data. Check example 9.

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 10.
  • Be careful when one replacement could be the search term of the subsequent search element. Check example 11.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP str_ireplace() Function

str_ireplace() 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-ireplace