stone stone - 8 days ago 5
PHP Question

preg_match and a troublesome regex

Could some one tell me why

//string
$content = 'random ${one.var} ${two.var} random';

//match
preg_match('/(?:(?<=\$\{))([\w.]+){1}(?=\})/i', $content, $matches);


is returning

print_R($matches);

//output
array(
[0]=>one.var
[1]=>one.var
);


What i want is

array(
[0]=>one.var
[1]=>two.var
);

Answer

Both the whole regex (0) as the inner capture () (1) match the same thing, so that part of the match makes sense. You probably want preg_match_all, which captures all matches...

preg_match_all('/(?<=\$\{)[\w.]+(?=\})/i', $content, $matches);
Comments