I'm wondering what is the quickest way to replace certain characters in a string with nothing. I now have the following:
$omschrijving = str_replace(")", "", str_replace("(", "", $line)));
Is there a better way to do this? This is only replacing the "("
and ")"
, but what if I want to do the same with more characters. Still learning the preg_
methods but it's still a bit of mind blowing at the moment.
str_replace
can also take arrays as parameters.This will do what you want, using preg_replace.
This will replace all instances of '(' and ')' in a string if you want to add something else just add it with in the square bracket.
For instance to add replace all dashes as well just add it to the replacement string.
Or to also replace all underscores.
Hope this helps.
Here you go:
From the manual:
According to my benchmarks, you have to use
str_replace
when replacing 1 or 2 characters at once. Whenever you have 3 or more characters to replace,preg_replace
is more efficient.I used this benchmark protocole, modifying it so it accepts various characters instead of one.
For 3 characters, here are the results:
no problem
str_replace
accpets array as 1st and 2nd argument.You can also use
strtr
,substr_replace
orpreg_replace
to replace string portions with something else.