Skip to content
Arie Visser

    Arie Visser ·

    Replace Multiple Items From String Text in PHP With Array

    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 str_replace.

    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 $search and $replace, each nth element from the $search array that is found in the $subject string, will be replaced by the nth item from the $replace array.

    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".