2011-10-04 55 views
0

我有模式问题。 我需要处理一些文本,例如:解析器替换模式

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

的过程中,我需要的地方{文本1}和{}文本2从字典一些话来获取后。 我正在准备用于不同语言的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>'); 

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

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

但我想要匹配的图案

{bodynum} and then {innernum} 

有人可以帮我解决这个问题。谢谢。

解决方案:

为了匹配之间{和}的任何字符,但不要贪 - 匹配与结束的最短串}(在停止+贪婪?)。

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

+1

我解决了这个问题!匹配{和}之间的任何字符,但不要贪婪 - 匹配以}结尾的最短字符串(“停止+正在贪婪)”。 –

回答

0

正如你正确的评论请注意,您可以使用一个ungreedy match在第一右括号停止而不是最后:

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

正如Damien所说,您还可以使用/U修改更缺乏默认的所有比赛。

或者,你可以限制设定在大括号之间允许某些字符集不包括}

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

甚至:

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

只允许word characters括号之间。由于PCRE引擎的工作方式,这可能(或者可能不会)比使用非理性匹配更有效率。当然,在实践中,不太可能有任何明显的差异。

0

你应该在你的模式中使用'U'修饰符。 More

0

尝试

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

Reference