使用数据库中的数组 str_replace($search, $replace, $string) - 具有动态值

Use Arrays from Database for str_replace($search, $replace, $string) - with dynamic values

如果我在我的源代码中定义内联数组,它就可以工作。但是我如何使用数据库中的变量名呢?

虽然我开发了这段代码,但我使用了一个内联定义的数组。但是现在我想从数据库中获取 $search$replace 元素。

我的问题{var}不再替换为$var的值,而是替换为字符串"$var".

$template_tags = array(
    '{order_id}',
    '{customer_id}'
);

$replacements = array(
    $insert_id,
    $mail_customer_id
);

// works: str_replace($template_tags, $replacements, $source) is for example "The Customer 0123 has the Order-ID 0987"

但是如果我从数据库中得到 $template_tags$replacements(只有 var 名称,var 值之前在源代码中设置),结果是:

"The Customer $mail_customer_id has the Order-ID $insert_id"

我的目标是我可以从数据库中获取变量名称,并将它们替换为定义前的值

我的数据库结果是:

Array ( [0] => {order_id} 
        [template_tag] => {order_id} 
        [1] => $order_id 
        [replacement] => $order_id ) 
Array ( [0] => {customer_id} 
        [template_tag] => {customer_id} 
        [1] => $customer_id 
        [replacement] => $customer_id )

编辑:

这段代码带来了我想要的结果——但它看起来不是很优雅,我不想使用eval,因为它有风险:

while ($value = mysqli_fetch_array($replacement_tags_query)) {
    $replacements[] = $value['replacement'];
    $template_tags[] = $value['template_tag'];
}
$str = str_replace($template_tags, $replacements, $testtext);
eval ("$str = \"$str\";");
echo $str;

请注意您来自数据库的值 return 是字符串:作为 '$order_id' 因此它们不会在代码中求值。

如果您想动态设置值,可以使用 PHP variable 功能。所以你需要做的就是从你的数据库中删除 '$' 标志并执行类似的操作:

while ($value = mysqli_fetch_array($replacement_tags_query))
{
    $replacements[] = ${$value['replacement']};
    $template_tags[] = $value['template_tag'];
}

现在您可以将其用于:str_replace($template_tags, $replacements, $string)