解析器替换模式


Parser replace pattern

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

<div>{text1}</div><span>{text2}</span>

在这个过程之后,我需要从字典中获得{text1}和{text2}的一些单词。我正在为不同的语言准备ui界面。这是在PHP中。现在我有这样的东西,但这不起作用:

function translate_callback($matches) {
  global $dict;
  print_r($matches);
  return 'replacement';
}
function translate($input) {
  return preg_replace_callback('/('{.+'})/', 'translate_callback', $input);
}
echo translate('<div>{bodynum}</div><span>{innernum}</span>');

这是一个测试场景,但是我找不到定义模式的方法,因为这个在代码匹配

{bodynum}</div><span>{innernum}

但是我想要匹配

{bodynum} and then {innernum}
有人能帮我一下吗?谢谢。

解决方案:

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

所以模式现在看起来像:'/{(.+?)}/',这正是我想要的。

正如您在注释中正确注意到的那样,您可以使用非贪婪匹配来停止在第一个右括号处,而不是最后一个:

preg_replace_callback('/('{.+?'})/', 'translate_callback', $input);

正如Damien所指出的,您还可以使用/U修饰符使所有匹配在默认情况下都是非贪婪的。

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

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

甚至:

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

只允许在大括号之间使用单词字符。由于PCRE引擎的工作方式,这可能(也可能不)比使用非贪婪匹配更有效。当然,在实践中,不太可能有任何可观察到的差异。

您应该在模式中使用'U'修饰符。更多的

try with

// 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];  
    }  
}
参考