RE: [PHP] Bug in look-behind assertions in PCRE patterns ?
| From: | Michael Sims | Date: | Wed, 23 Mar 2005 16:50:11 +0000 |
| Subject: | RE: [PHP] Bug in look-behind assertions in PCRE patterns ? | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-211391@lists.php.net to get a copy of this message | ||
Ian Thurlbeck wrote:
> Dear All
>
> Is this a bug ?
[...]
> $line = '$res = $bar("ddd", "dfdf");';
> if (preg_match("/(?<!\$)(bar)/", $line, $matches)) {
> echo "Should NOT match \$bar, but found: ".$matches[1];
> }
> ----------------
>
> In the first preg_match() is correctly ignores the foobar
> function name. However the second preg_match() does NOT
> ignore the $bar as I expected.
This is a quoting issue. Above you are using double quotes, which interpolates
embedded PHP variables. Therefore if you want a literal "$" inside a double-quoted
string you have to escape it, as you have done. However, the "$" character is ALSO
a preg metacharacter (matches end of line). This means that you must also escape it
for the preg parser as well, so you need to escape it twice, by putting another
literal backslash behind it:
if (preg_match("/(?<!\\\$)(bar)/", $line, $matches)) {
Either that or you can use single quotes instead of double quotes:
if (preg_match('/(?<!\$)(bar)/', $line, $matches)) {
Either one will work.
HTH