开发者

Regular expression inclusion trouble

I am trying to process some PHP code to extract keys from a specific array. I am using regular expressions to do so.

A sample source text :

$src = 'if ( $loc["key"] == $val) { // some stuff }';

The regex code :

preg_match_all('/\$loc\[\"(.+)\"]/',$src,$keys);

Which gives me the right answer :

key

But if change src to :

$src = 'if (开发者_StackOverflow $loc["key"] == $val ) { $loc["otherkey"] == $val; }';

It gives :

key"] == $val ) { $loc["otherkey

Does anyone have any idea why is it like this, and how to resolve this ?


You need to make the dot ungreedy by appending "U" to your expression:

preg_match_all('/\$loc\[\"(.+)\"]/U',$src,$keys);

Or replace the dot with the "but not quote" expression:

preg_match_all('/\$loc\[\"([^"]+)\"]/',$src,$keys);


Make + non-greedy(lazy):

/\$loc\["(.+?)"\]/

Otherwise, it tries to match as many characters as possible (.+) until it finds another " (the last one).

Or maybe better is to match all characters except double quotes:

 /\$loc\["([^"]+)"\]/

Btw, as you use single quotes for the expression, you don't need to escape the double quotes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜