How to Use str_replace with Arrays in PHP
The str_replace() function in PHP is a highly versatile
tool for replacing occurrences of a search string with a replacement
string. When dealing with arrays as arguments, its behavior scales to
handle complex string manipulations: you can pass arrays for the search
terms, the replacement terms, the subject string, or all three. This
article explains exactly how PHP processes these array arguments,
detailing the interactions between different combinations of string and
array parameters.
1. Array as the Search Argument
If you pass an array as the first argument ($search) and
a string as the second argument ($replace), PHP will search
for every element in the $search array and replace it with
the single $replace string.
$search = ['apple', 'banana', 'cherry'];
$replace = 'fruit';
$subject = 'I like apple, banana, and cherry.';
$result = str_replace($search, $replace, $subject);
// Output: "I like fruit, fruit, and fruit."2. Arrays as Search and Replace Arguments
When both $search and $replace are arrays,
PHP maps elements from the search array to the replacement array based
on their keys.
- Equal-sized arrays: The first element of
$searchis replaced by the first element of$replace, the second by the second, and so on. - Fewer replacement elements: If the
$replacearray has fewer elements than the$searcharray, any leftover search elements that do not have a corresponding replacement element will be replaced by an empty string ("").
$search = ['red', 'green', 'blue'];
$replace = ['warm', 'cool']; // Fewer elements than $search
$subject = 'The light is red, green, and blue.';
$result = str_replace($search, $replace, $subject);
// Output: "The light is warm, cool, and ."3. Array as the Subject Argument
If the third argument ($subject) is an array, the
search-and-replace operation runs on every single item within that
array. The function then returns an array containing the modified
strings instead of a single string.
$search = 'bad';
$replace = 'good';
$subjects = ['This is bad', 'That is bad', 'Everything is fine'];
$result = str_replace($search, $replace, $subjects);
// Output: ['This is good', 'That is good', 'Everything is fine']Crucial Rule: Order of Operations
When passing arrays to str_replace(), the replacements
are processed sequentially from left to right. Because of this, a value
replaced in an earlier step can be replaced again by a subsequent search
term in the same array.
$search = ['A', 'B'];
$replace = ['B', 'C'];
$subject = 'A';
$result = str_replace($search, $replace, $subject);
// Output: "C"
// Explanation: 'A' becomes 'B' first, then 'B' becomes 'C'.