开发者

Change str_replace() in loop to single preg_replace() call?

How 开发者_Go百科do you change this to a preg_replace() equivalent (without using a loop)?

Note: $text is utf-8.

  do $text = str_replace("* *", "*", $text, $totRepla); while ($totRepla);


I believe the regexp pattern to match an arbitrary long * * * * * * is

/(\* )*\*/

Please add the rest of the code yourself, I don't have PHP handy right now to provide a full code snippet.


Actually, String functions are much more efficient then regex, I see no reason using regex if you have a working solution using str_replace.

http://php.net/manual/en/function.str-replace.php

see documentation:

If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of preg_replace().


preg_replace('/\* \*/', '*', $totRepla);


The PCRE equivalent of that is:

$text = preg_replace('~(?:[*] )+[*]~', '*', $text);

Your code suggests that you have no interest in knowing how many replacements occurred, so you don't need the $totRepla variable. However, if I am wrong, this is the way to get that count:

$text = preg_replace('~(?:[*] )+[*]~', '*', $text, -1, $totRepla);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜