gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:56:44 34 4
gpt4 key购买 nike

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

但是它有一些问题。首先是当我 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.'

最佳答案

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

$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 - 替换字符串中的占位符变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15773349/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com