Quickest way to replace a series of characters in

2019-07-27 10:17发布

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.

5条回答
再贱就再见
2楼-- · 2019-07-27 10:58

str_replace can also take arrays as parameters.

$omschrijving = str_replace(array('(', ')'), '', $line);
查看更多
甜甜的少女心
3楼-- · 2019-07-27 11:14

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.

查看更多
看我几分像从前
4楼-- · 2019-07-27 11:18

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.

查看更多
Bombasti
5楼-- · 2019-07-27 11:20

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

查看更多
放我归山
6楼-- · 2019-07-27 11:21

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.

查看更多
登录 后发表回答