Case-Insensitive String Replacement in PHP
This article explains how to perform case-insensitive string
replacement in PHP using the built-in str_ireplace()
function. You will learn the basic syntax of the function, how it
differs from str_replace(), and see practical examples of
how to replace single words as well as multiple values using arrays.
The str_ireplace() function is the case-insensitive
version of str_replace(). It searches a subject string for
a specific value and replaces it with a new value, ignoring whether the
characters are uppercase or lowercase.
Syntax of
str_ireplace()
The function accepts four parameters:
str_ireplace(mixed $search, mixed $replace, mixed $subject, int &$count = null): mixed$search: The value being searched for (can be a string or an array).$replace: The replacement value (can be a string or an array).$subject: The string or array being searched and replaced on.$count(Optional): A variable that will be filled with the number of matched and replaced needles.
Basic Example
In this example, the word “apple” is searched in a case-insensitive manner and replaced with “orange”.
$text = "I love eating Apple pie and APPLES.";
$new_text = str_ireplace("apple", "orange", $text);
echo $new_text;
// Output: I love eating orange pie and oranges.As demonstrated, both “Apple” (capitalized) and “APPLES” (uppercase) are successfully matched and replaced.
Using Arrays with
str_ireplace()
You can pass arrays to both the search and replacement parameters to perform multiple replacements at once.
$search_words = ["BROWN", "FOX", "LAZY"];
$replacements = ["white", "cat", "playful"];
$phrase = "The quick Brown Fox jumps over the lazy dog.";
$new_phrase = str_ireplace($search_words, $replacements, $phrase);
echo $new_phrase;
// Output: The quick white cat jumps over the playful dog.Tracking the Number of Replacements
If you need to know how many replacements were made during the operation, pass a variable as the fourth argument.
$text = "Go green, think Green, live green.";
$new_text = str_ireplace("green", "blue", $text, $count);
echo $new_text; // Output: Go blue, think blue, live blue.
echo "Replacements made: " . $count; // Output: Replacements made: 3