如何preg_replace {{ }}之间的内容

How to preg_replace content between {{ }}

下面是我的代码,用来替换{{ }}之间的内容。例如,我使用 {{example}} 从数据库加载自定义文本以替换 html 输出中的内容。这很有效,但有时却行不通,我不确定为什么。如果我使用两个 {{one}} 和 {{two}} ,它可能在同一行中。所以我想也许我做错了 preg_replace

function translate($tagname){
   global $$tagname;
   return $$tagname;
}

function replaceTags($body){
   $body = preg_replace('!{{(.*?)}}!Uei', "''.translate('').''", $body);
   return $body;
}

你应该放弃 U 修饰符,因为它会使你的贪婪 (.*?) 变得贪婪,而这不是你想要的。

此外,e 修饰符在 PHP 5.5.0 中已弃用。使用 preg_replace_callback 代替:

$firstName = 'Jane';
$lastName = 'Doe';

function translate($tagname){
    global $$tagname;
    return $$tagname;
}

function translateMatch($matches) {
    return translate($matches[1]);
}

function replaceTags($body){
    $body = preg_replace_callback('!{{(.*?)}}!i', 'translateMatch', $body);
    return $body;
}

echo replaceTags("Hello, {{firstName}} {{lastName}}!"), PHP_EOL;

输出:

Hello, Jane Doe!