2012-02-22 60 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