RE: preg_match() is returning inaccurate result

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



In more detail, `\$third` gets de-escaped when the double-quoted string is parsed. And the regular _expression_ parser is left with just `$third`.
If you use `\\$third`, `\\` gets de-escaped to `\` and `$third` is treated as a variable (not what you want).
If you use `\\\$third`, then the regular _expression_ parser gets both `\` and `$` preserved, which is what you want: `\$third`.

Your second example returned `TRUE` because `$third` was actually evaluated to an empty string, and `'xyz$third-party'` does end with `-party` indeed.
This second example probably triggered a warning, too - about an undefined variable `$third`. So I suggest you pay attention to PHP warnings and notices as well, as that would have probably lead you to the right direction when trying to understand what was happening.

Regards,
Janis


No: Jigar Dhulla <jigar.tidus@xxxxxxxxx>
Nosūtīts: otrdiena, 2024. gada 23. aprīlis 08:02
Kam: php-general@xxxxxxxxxxxxx <php-general@xxxxxxxxxxxxx>
Tēma: Re: preg_match() is returning inaccurate result
 


On Tue, Apr 23, 2024 at 8:02 AM <0xabeef@xxxxxxxxxx> wrote:
PHP8.3.4

Can someone help? preg_match() is acting weird about \$ and \^.

var_dump(preg_match("/\$third-party$/",'xyz$third-party')?true:false);//
returns FALSE, really expecting TRUE here!
var_dump(preg_match("/$third-party$/",'xyz$third-party')?true:false);//
returns TRUE???

^ and $ must escape if it is not in beginning/ending position.
Isn't this correct?

At least _javascript_ is answering correctly.

/\$third-party$/.test('xyz$third-party'); // TRUE
/$third-party$/.test('xyz$third-party'); // FALSE
Hi,

double quotes ("") around a string are evaluating `$third` as a variable in the first argument.

Use single quotes ('') instead.
var_dump(preg_match('/\$third-party$/','xyz$third-party')?true:false);
var_dump(preg_match('/$third-party$/','xyz$third-party')?true:false);

Playground: https://onlinephp.io/c/52068

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux