2013-10-26 119 views
0

我需要在花括号中提取文本,但前提是它们中的第一个单词是“允许”单词。 例如下面的文字:preg_match返回奇怪的结果

awesome text, 
a new line {find this braces}, 
{find some more} in the next line. 
Please {dont find} this ones. 

在这个简单的例子, “发现” 代表允许字

我学尝试:

$pattern  = '!{find(.*)}!is'; 
$matches  = array(); 
preg_match_all($pattern, $text, $matches, PREG_SET_ORDER); 

返回怪异的结果(print_r的):

Array 
(
    [0] => Array 
     (
      [0] => {find this braces}, 
    {find some more} in the next line. 
    Please {dont find} 
      [1] => this braces}, 
    {find some more} in the next line. 
    Please {dont find 
     ) 

) 

虽然工作正常,但没有“发现”的模式(但然后吨他也找到了一个“不”。

这可能是什么原因造成的?

回答

3

.*将贪婪的匹配,即尽可能possible.Use .*?匹配懒洋洋地即尽可能少

所以,你的正则表达式将是

!{find(.*?)}!is 

或者您可以使用[^{}]代替.*? ..在这种情况下,你不需要使用单线模式

!{find([^{}]*)}!i 
+0

你比我快:p – nut

+0

@nut我想我是第一个看到这个问题的人;;) – Anirudha

+0

加入问号的工作。谢谢! – iceteea