2011-11-28 88 views
1

我这个小码括号内捕获文本的文本:如何捕捉括号内

$string = '[title=my title] http://bit.ly/gANFxi [maps:some cool place]';  
preg_match_all('/\[([^\]]*)\]/', $string, $matches); 
print_($matches[0]); 

我得到的是以下几点:

 
    Array(
     [0] => [title=my title] 
     [1] => [maps:some cool place] 
    ) 

我要让更多的限制,以避免“ [some-not cool]“或者”[another + stuff]“, ,所以我只需要抓住[some:thing]和[some = thing]。

我该怎么办?

回答

2

这将赶上一个包含“=”或一切“:”而忽略其他:

$string = '[title=my title] http://bit.ly/gANFxi [maps:some cool place] [some-not cool] or [another+stuff]'; 
preg_match_all('/\\[([^\\]]*[\\=|\\:][^\\]]*)\\]/', $string, $matches); 
print_r($matches[0]); 

这是否做的伎俩?还是有进一步的要求?也就是说,这个回报“[some stuff = some:thing]”,但是它应该如何? (注意多个单词以及'='和':')。

+0

就是这样!谢谢:D – greenbandit

+1

世界需要更多的正则表达式专家 –

+0

@AdamSack,世界需要更多的Chomskys。 – Godwin

1

如果等于应仅由字母冒号或之前的部分,你可以使用下面的代码:

preg_match_all('/\[([a-z]+[:=][^\]]+)\]/i', $string, $matches); 

如果第一部分是一些更类似于一个PHP标识符(除您可以使用以下代码:

​​