144

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.

2
  • 2
    you want to replace all these chars with a space? Sep 30, 2011 at 2:53
  • 7
    Don't be afraid to reference the excellent php.net manual and review the params section to see if what you want is possible.
    – Mike B
    Sep 30, 2011 at 2:57

10 Answers 10

239

Like this:

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

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

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

str_replace() can take an array, so you could do:

$new_str = str_replace(str_split('\\/:*?"<>|'), ' ', $string);

Alternatively you could use preg_replace():

$new_str = preg_replace('~[\\\\/:*?"<>|]~', ' ', $string);
6
  • 2
    Assuming the OP meant that the backslash should be replaced, that preg_replace pattern didn't work for me. To get the backslash to work as expected, I had to use 4 of them (i.e. "\\\\") in the pattern.
    – GreenMatt
    Sep 30, 2011 at 4:13
  • 1
    Good answer, adding @dogbert answer in would make it complete for the people who don't read the manual and don't realise str_split returns an array.
    – Bradmage
    Dec 31, 2015 at 23:13
  • What's the advantage of str_replace() over preg_replace() (or vice-versa) in the OP's case? Feb 12, 2019 at 20:36
  • 1
    @ludditedev No real advantage either way, it's just a matter of preference Feb 23, 2019 at 16:57
  • 1
    @MadhurBhaiya Change the regex to '~[\\+><-]~' (note where the - is). The dash (-) is a regex metacharacter, so it needs to escaped or strategically placed in the character class (everything inside []). See this answer: stackoverflow.com/a/7604888/396458 Sep 17, 2019 at 17:21
99

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

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

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

1
  • 3
    Single characters only? How come?
    – Jimmy Kane
    Jul 31, 2014 at 13:41
3

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          "

1
  • Too much escaping inside the character class. (see accepted answer) Apr 21, 2018 at 6:31
1

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

0

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);
}
0

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'); ?>
0

preg_replace() is the best for multiple items. Please check:

$invoice_no = preg_replace('~[\\+:><-]~', "",rand(0, 10) . now());

For single replacement you can use str_replace() :

$invoice_no = str_replace("-", "",rand(0, 1000) . now());

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.