How to use str_replace in PHP 8

Description

The str_replace function is useful for replacing various strings with replacement strings.

str_repplace in PHP 8

str_replace(
    array|string $search,
    array|string $replace,
    string|array $subject,
    int &$count = null
): string|array

Parameters

In the simplest form, the str_replace function returns the altered string $subject by replacing all occurrences of $search with the replacement string $replace.

Alternatively, you can also provide an array for $search and $replace. You can't mix a string with an array for these parameters. By providing arrays for both parameters, you can designate replacement values for each search term in the $search array.

  1. $search

    This is the needle or needles that should be looked for in the $subject string.
  2. $replace

    The replacement value or values that corresponds to the $search value or values.
  3. $subject

    This is the string on which the replacement operation should be executed on. Typically this is called the haystack. In case the $subject is an array, the replacement operation is executed on each instance of the array and the return value of the function will be an array containing the altered strings.
  4. &$count (optional)

    If you pass an additional $count parameter, str_replace will set it to the successful amount of replacements in the $subject.

Examples

echo str_replace("test", "world", "Hello test!");

Hello world!

In this example, the str_replace function replaces the word "test" with the word "world" and returns the final string "Hello world!".

echo str_replace("test", "world", "Hello test! Hello test!");

Hello world! Hello world!

This example is similar to the previous. It illustrates that every occurrence of the word "test" is replace by the word "world".

$result = str_replace("test", "world", ["Hello test!", "Hello test!"]);

foreach ($result as $item) {
    echo $item . "\n";
}

Hello world!
Hello world!

This example illustrates that you can provide several subjects as an array. The str_replace function will then run on each item of the array.

echo str_replace(["test", "toast"], ["world", "world"], "Hello test! Hello toast!", $count);

echo "\nReplaced: " . $count;

Hello world! Hello world!
Replaced: 2

The last example shows you how to use an array of $search needles and an array of replacement strings as $replace paramter. The $count parameter is correctly set to 2 as 2 substrings have been replaced.