|
Posted by Michael Sims on 10/02/11 11:12
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
Navigation:
[Reply to this message]
|