php 使用关联数组中的数据替换mustache占位符[重复]

vwkv1x7d  于 2023-02-03  发布在  PHP
关注(0)|答案(2)|浏览(118)
    • 此问题在此处已有答案**:

what is the efficient way to parse a template like this in php?(3个答案)
str_replace() with associative array(5个答案)
PHP - Replacing multiple sets of placeholders while looping through arrays(1个答案)
How do I use preg_replace in PHP with {{ mustache }}(1个答案)
(13个答案)
昨天关门了。
如何编写自定义php函数,通过传递函数参数将变量替换为值?

$template = "Hello, {{name}}!";

$data = [
    'name'=> 'world'
];

echo replace($template, $data);

function replace($template, $data) {

    $name = $data['name'];
    
    return $template;
    
}

回显替换($模板,$数据);必须返回"你好,世界!"谢谢!

n1bvdmb6

n1bvdmb61#

一种方法是使用内置的str_replace函数,如下所示:

foreach($data as $key => $value) {
  $template = str_replace("{{$key}}", $value, $template);
}

return $template;

这将循环数据数组并将键替换为值。

os8fio9y

os8fio9y2#

您可以使用preg_replace_callback_array来执行正则表达式搜索并使用回调进行替换。
这个解决方案适用于多个变量,它解析整个文本,并交换每个指定的变量。

function replacer($source, $arrayWords) {
    return preg_replace_callback_array(
        [
            '/({{([^{}]+)}})/' => function($matches) use ($arrayWords) {
                if (isset($arrayWords[$matches[2]])) $returnWord = $arrayWords[$matches[2]];
                else $returnWord = $matches[2];
                return $returnWord;
            },
        ], 
        $source);
}

demo here

相关问题