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.
Here you go:
str_replace(array('a', 'b', 'c', 'd'), '', $sString);
From the manual:
The replacement value that replaces found search values. An
array may be used to designate multiple replacements.
str_replace
can also take arrays as parameters.
$omschrijving = str_replace(array('(', ')'), '', $line);
no problem
$omschrijving = str_replace(array('a', 'b', 'c', 'd', 'e', 'f', 'g'), "", $line);
str_replace
accpets array as 1st and 2nd argument.
You can also use strtr
, substr_replace
or preg_replace
to replace string portions with something else.
This will do what you want, using preg_replace.
$string = preg_replace('/[()]/i', '', $string);
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.
$string = preg_replace('/[()-]/i', '', $string);
Or to also replace all underscores.
$string = preg_replace('/[()_-]/i', '', $string);
Hope this helps.
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:
Time for str_replace: 1.919958114624 seconds Time for preg_replace:
1.4596478939056 seconds