替换字符串中的占位符变量

2022-08-30 22:31:42

刚刚完成这个功能。基本上,假设要查看字符串并尝试查找任何占位符变量,这些变量将位于两个大括号之间 。它获取大括号之间的值,并使用它来查看应与键匹配的数组。然后,它将字符串中的大括号变量替换为匹配键数组中的值。{}

不过它有一些问题。首先是当我把结果放在数组中时,放在数组内。所以我必须使用两个只是达到正确的数据。var_dump($matches)foreach()

我也觉得它很重,我一直在研究它,试图让它变得更好,但我有点被难住了。我错过了任何优化?

function dynStr($str,$vars) {
    preg_match_all("/\{[A-Z0-9_]+\}+/", $str, $matches);
    foreach($matches as $match_group) {
        foreach($match_group as $match) {
            $match = str_replace("}", "", $match);
            $match = str_replace("{", "", $match);
            $match = strtolower($match);
            $allowed = array_keys($vars);
            $match_up = strtoupper($match);
            $str = (in_array($match, $allowed)) ? str_replace("{".$match_up."}", $vars[$match], $str) : str_replace("{".$match_up."}", '', $str);
        }
    }
    return $str;
}

$variables = array("first_name"=>"John","last_name"=>"Smith","status"=>"won");
$string = 'Dear {FIRST_NAME} {LAST_NAME}, we wanted to tell you that you {STATUS} the competition.';
echo dynStr($string,$variables);
//Would output: 'Dear John Smith, we wanted to tell you that you won the competition.'

答案 1

我认为对于这样一个简单的任务,您不需要使用正则表达式:

$variables = array("first_name"=>"John","last_name"=>"Smith","status"=>"won");
$string = 'Dear {FIRST_NAME} {LAST_NAME}, we wanted to tell you that you {STATUS} the competition.';

foreach($variables as $key => $value){
    $string = str_replace('{'.strtoupper($key).'}', $value, $string);
}

echo $string; // Dear John Smith, we wanted to tell you that you won the competition.

答案 2

我希望我不会太晚加入这个派对 - 这是我将如何做到的:

function template_substitution($template, $data)
{
    $placeholders = array_map(function ($placeholder) {
        return strtoupper("{{$placeholder}}");
    }, array_keys($data));

    return strtr($template, array_combine($placeholders, $data));
}

$variables = array(
    'first_name' => 'John',
    'last_name' => 'Smith',
    'status' => 'won',
);

$string = 'Dear {FIRST_NAME} {LAST_NAME}, we wanted to tell you that you have {STATUS} the competition.';

echo template_substitution($string, $variables);

而且,如果有机会你可以让你的键完全匹配你的占位符,那么解决方案就变得非常简单:$variables

$variables = array(
    '{FIRST_NAME}' => 'John',
    '{LAST_NAME}' => 'Smith',
    '{STATUS}' => 'won',
);

$string = 'Dear {FIRST_NAME} {LAST_NAME}, we wanted to tell you that you have {STATUS} the competition.';

echo strtr($string, $variables);

(参见 PHP 手册中的 strtr()。

考虑到PHP语言的性质,我相信这种方法应该从这个线程中列出的所有语言中产生最佳性能。


编辑:在7年后重新审视了这个答案后,我注意到我这边有一个潜在的危险疏忽,另一个用户也指出了这一点。一定要以赞成票的形式拍拍他们的背!

如果您对此编辑之前的答案感兴趣,请查看修订历史记录


推荐