首页  >  文章  >  后端开发  >  如何高效替换字符串中的占位符变量?

如何高效替换字符串中的占位符变量?

Susan Sarandon
Susan Sarandon原创
2024-11-23 07:05:10249浏览

How Can I Efficiently Replace Placeholder Variables in a String?

优化“替换字符串中的占位符变量”

人们可能会遇到各种场景,其中识别和替换字符串中的占位符变量至关重要。此代码片段演示了一个动态替换函数 dynStr,它可以定位大括号 ({}) 括起来的键值对并相应地更新它们:

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.'

但是,正如作者强调的那样,此实现存在冗余数组访问并且显得计算密集。我们可以通过消除正则表达式的使用并根据“vars”数组中的键值对实现简单的字符串替换来简化这一过程:

$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.

这种方法删除了不必要的嵌套数组遍历,并且简化替换过程,从而产生更干净、更高效的代码。

以上是如何高效替换字符串中的占位符变量?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn