phpstringreplace

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.


Solution

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