[php] Str_replace for multiple items

I remember doing this before, but can't find the code. I use str_replace to replace one character like this: str_replace(':', ' ', $string); but I want to replace all the following characters \/:*?"<>|, without doing a str_replace for each.

This question is related to php string str-replace

The answer is


I had a situation whereby I had to replace the HTML tags with two different replacement results.

$trades = "<li>Sprinkler and Fire      Protection Installer</li>
<li>Steamfitter </li>
<li>Terrazzo, Tile and Marble      Setter</li>";

$s1 =  str_replace('<li>', '"', $trades);

$s2 = str_replace('</li>', '",', $s1);

echo $s2;

result

"Sprinkler and Fire Protection Installer", "Steamfitter ", "Terrazzo, Tile and Marble Setter",


You could use preg_replace(). The following example can be run using command line php:

<?php
$s1 = "the string \\/:*?\"<>|";
$s2 = preg_replace("^[\\\\/:\*\?\"<>\|]^", " ", $s1) ;
echo "\n\$s2: \"" . $s2 . "\"\n";
?>

Output:

$s2: "the string          "


Like this:

str_replace(array(':', '\\', '/', '*'), ' ', $string);

Or, in modern PHP (anything from 5.4 onwards), the slighty less wordy:

str_replace([':', '\\', '/', '*'], ' ', $string);

For example, if you want to replace search1 with replace1 and search2 with replace2 then following code will work:

print str_replace(
    array("search1","search2"),
    array("replace1", "replace2"),
    "search1 search2"
);

// Output: replace1 replace2


I guess you are looking after this:

// example
private const TEMPLATE = __DIR__.'/Resources/{type}_{language}.json';

...

public function templateFor(string $type, string $language): string
{
   return \str_replace(['{type}', '{language}'], [$type, $language], self::TEMPLATE);
}

If you're only replacing single characters, you should use strtr()


In my use case, I parameterized some fields in an HTML document, and once I load these fields I match and replace them using the str_replace method.

<?php echo str_replace(array("{{client_name}}", "{{client_testing}}"), array('client_company_name', 'test'), 'html_document'); ?>

str_replace(
    array("search","items"),
    array("replace", "items"),
    $string
);