2012-02-22 56 views
0

能有人告诉我,为什么的preg_match和麻烦的正则表达式

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

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

正在恢复

print_R($matches); 

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

我想是

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

回答

2

作为内部捕获()(1)的整个正则表达式(0)都匹配相同的东西,所以部分匹配是有意义的。你可能想preg_match_all,捕捉所有比赛......

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

您应该使用preg_match_all执行全局正则表达式搜索,也 - 我认为你可以这样简化模式:

preg_match_all('/\$\{(.*?)\}/', $content, $matches) 
+0

谢谢。但我不需要'$ {'和'}'位。观察周围的原因。从来不知道我需要preg_match_all来代替/ g修饰符。谢谢。现在用'(?:(?<= \ $ \ {))(。*?)(?= \})返回'array(数组( [0] => one.var [1] = > two.var ),阵列( [0] => one.var [1] => two.var ))' – stone 2012-02-22 20:54:32