forgodsakehold
forgodsakehold

Reputation: 904

Regex in PHP expecting to match strings like "${string}" not working

I’ve got:

$ap=0;
$matches=array();
d($ap, $vv[$value],$matches);
$ap = preg_match("/\$[({].+[)}]/", $vv[$value], $matches);
d($ap, $vv[$value],$matches);

d() is a custom function like var_dump().

When $vv[$value] is "exec_prefix = ${prefix}", why is that $ap is 0, and there’s no matches ($matches is still an empty array)?

I am expecting "${prefix}" to be matched.

I tried the regex in regexpal.com and it matches too.

Upvotes: 2

Views: 66

Answers (2)

Sin Sopheak
Sin Sopheak

Reputation: 364

The "\" before "$" is removed before it gets to preg_match() because it is treated by PHP as an escape character for "$".

To fix this, simply use single quote instead of double quote:

$ap = preg_match('/\$[({].+[)}]/', $vv[$value], $matches);

Upvotes: 1

Nigel Ren
Nigel Ren

Reputation: 57121

In your regex, you are trying to use $ as the start of field marker. As PHP needs the $ to be escaped otherwise it will think it's introducing a variable substitution (in double quotes) it will use the \ you've included for this purpose. BUT this then leaves the regex as

/$[({].+[)}]/

and this means it will use the $ as the end of string marker - and therefore not find the content your after.

So, you need a second escape before the dollar to make sure it is picked up properly...

$ap = preg_match("/\\$[({].+[)}]/", $vv[$value], $matches);

Upvotes: 2

Related Questions