Re: preg_replace does not replace all occurrences
| From: | Ben Schmidt | Date: | Mon, 14 Mar 2011 18:44:47 +0000 |
| Subject: | Re: preg_replace does not replace all occurrences | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-51686@lists.php.net to get a copy of this message | ||
On 15/03/11 5:38 AM, Ben Schmidt wrote:
On 15/03/11 2:18 AM, Martin Scotta wrote:Actually, no it doesn't. The behaviour is correct. Matches cannot overlap. Since the character preceding 'b' is part of the match, there is only one match in the string 'str bb str'. The match is ' b'. After that match, the You actually want an assertion. I think this: static $re = '/(^|(?<!a))b/'; Ben.I chose the simplest example to show the preg_replace behavior,You've GOT to be kidding. The SIMPLEST?! How about an example that doesn't require escaping ALL the interesting characters involved? Here's a modified version that I think it quite a bit simpler: <?php function test($str) { static $re = '/(^|[^a])b/'; static $change = '$1ab'; echo $str, PHP_EOL; // input echo preg_replace($re, $change, $str), PHP_EOL, PHP_EOL; // output } test("str bb str"); // bug? test("str abab str"); // ok test("b str b"); // ok test("ab str ab"); // ok ?> The way I interpret it, it should put an 'a' before every 'b' that is not already preceded by an 'a'. But the buggy case gives 'str abb str' rather than the expected 'str abab str'. It does look like a bug to me.