2010-08-21 104 views
1

的內容我有一個字符串得到匹配元素

$str = "this is [start] my string [end] at this moment"; 

我需要得到內[start][end]內容。

當我使用

$result = preg_match('/\[start\].+\[end\]/',$str, $m); 

它mutches [start] my string [end],但我需要得到的只有my string(無空格)。

當然我可以做另一個preg_replace並刪除它們,但我認爲必須有更優雅的解決方案。

謝謝

回答

4

使用捕獲的組。

$result = preg_match('/\[start\](.+)\[end\]/',$str, $m); 
$matched = $m[1]; 

(請注意,如果有多個[start]/[end]組您正則表達式將失敗(需要懶惰量詞.+?),或嵌套[start]/[end]組(使用遞歸模式)。)


如果你不想要的空間,你可以避開它的正則表達式匹配:

$result = preg_match('/\[start\]\s*(.+?)\s*\[end\]/',$str, $m); 
$matched = $m[1]; 

Ø你只需撥打trim()即可。

$result = preg_match('/\[start\](.+)\[end\]/',$str, $m); 
$matched = trim($m[1]); 
+0

優秀。那麼空間呢? – Simon 2010-08-21 12:07:29

+0

@Syom:查看更新。 – kennytm 2010-08-21 12:12:01