Replace Multiple Items From String Text in PHP With Array
Arie Visser • October 24, 2023php
In this post I just want to show a very small trick I came across recently.
How to replace multiple items from a string in PHP at once?
You probably know the internal PHP function
When looking at the documentation, we can see that it is also possible to pass arrays as arguments:
str_replace( array|string $search, array|string $replace, string|array $subject, int &$count = null ): string|array
When you give an array for
nth element from the
$search array that is found in the
$subject string, will be replaced by the
nth item from the
You can combine this with the
array_keys function to replace multiple items from a string with an associative array.
Let me show an example to make it clear:
$subject = 'PHP is dead since 10 years ago'; $replace = [ 'is dead' => 'will be alive', 'since 10 years ago' => 'forever', ]; str_replace(array_keys($replace), $replace, $subject);
This will result in "PHP will be alive forever".