Php 解析器替换模式

Php 解析器替换模式,php,parsing,design-patterns,Php,Parsing,Design Patterns,我对图案有问题。 我需要处理一些文本,例如: <div>{text1}</div><span>{text2}</span> 有人能帮我吗。谢谢 解决方案: 要匹配{和}之间的任何字符,但不要贪婪-匹配以}结尾的最短字符串(停止+贪婪) 因此,模式现在看起来像:“/{(+?)}/”,这正是我想要的。您应该在模式中使用“U”修饰符 试试看 // this will call my_callback() every time it sees brack

我对图案有问题。 我需要处理一些文本,例如:

<div>{text1}</div><span>{text2}</span>
有人能帮我吗。谢谢

解决方案:

要匹配{和}之间的任何字符,但不要贪婪-匹配以}结尾的最短字符串(停止+贪婪)


因此,模式现在看起来像:“/{(+?)}/”,这正是我想要的。

您应该在模式中使用“U”修饰符

试试看

// this will call my_callback() every time it sees brackets  
$template = preg_replace_callback('/\{(.*)\}/','my_callback',$template);  

function my_callback($matches) {  
    // $matches[1] now contains the string between the brackets  

    if (isset($data[$matches[1]])) {  
        // return the replacement string  
        return $data[$matches[1]];  
    } else {  
        return $matches[0];  
    }  
}

正如您在评论中正确指出的那样,您可以使用一个右大括号在第一个右大括号处停止,而不是在最后一个右大括号处停止:

preg_replace_callback('/(\{.+?\})/', 'translate_callback', $input);
正如Damien所指出的,您还可以使用
/U
修饰符在默认情况下取消冻结所有匹配项

或者,您可以将大括号之间允许的字符集限制为不包含
}
的字符集:

preg_replace_callback('/(\{[^}]+\})/', 'translate_callback', $input);
甚至:

preg_replace_callback('/(\{\w+\})/', 'translate_callback', $input);

这只允许在大括号之间。由于PCRE引擎的工作方式,这可能(也可能不)比使用ungreedy匹配稍微更有效。当然,在实践中,不太可能有任何明显的差异。

我解决了这个问题!要匹配{和}之间的任何字符,但不要贪婪-匹配以}结尾的最短字符串(停止+贪婪)。
preg_replace_callback('/(\{.+?\})/', 'translate_callback', $input);
preg_replace_callback('/(\{[^}]+\})/', 'translate_callback', $input);
preg_replace_callback('/(\{\w+\})/', 'translate_callback', $input);