Str_replace for multiple items

247,202

Solution 1

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

Solution 2

Like this:

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

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

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

Solution 3

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

Solution 4

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

Solution 5

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

Share:
247,202
sameold
Author by

sameold

Updated on April 06, 2020

Comments

  • sameold
    sameold about 4 years

    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.

  • GreenMatt
    GreenMatt over 12 years
    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.
  • Jimmy Kane
    Jimmy Kane almost 10 years
    Single characters only? How come?
  • Bradmage
    Bradmage over 8 years
    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.
  • mickmackusa
    mickmackusa about 6 years
    Too much escaping inside the character class. (see accepted answer)
  • aronmoshe_m
    aronmoshe_m over 5 years
    What's the advantage of str_replace() over preg_replace() (or vice-versa) in the OP's case?
  • NullUserException
    NullUserException over 5 years
    @ludditedev No real advantage either way, it's just a matter of preference
  • Madhur Bhaiya
    Madhur Bhaiya almost 5 years
    @NullUserException let's say I want to remove all these characters: +->< . Based on your answer, I tried: preg_replace('~[\\+-><]~', '', $s); . But it is removing the digits also (0-9). What is wrong ? Demo at: 3v4l.org/inS5W
  • NullUserException
    NullUserException almost 5 years
    @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