How to Replace Multiple Characters with str_replace() in PHP
To replace multiple characters in a string, pass an array of characters to search for in the first argument of str_replace()
.
$string = 'This is a string-of-text';
$output = str_replace([' ', '-'], '', $string);
print($output);
Thisisastringoftext
In the above example, all whitespaces and dashes are replaced with an empty string.
It might be easier to read if the list of strings to replace is stored as a string then split into an array before being used by str_replace()
like this:
$string = 'This is a string-of-text';
$output = str_replace(str_split(' -'), '', $string);
print($output);
Thisisastringoftext