PHP 花括号替换多个值

时间:2021-01-31 04:57:03

标签: php

我想将值 lara 某些单词放在大括号中。但结果它给了我 $ str 。所以它向我展示了相同的词,没有进行任何替换。

我尝试如下:

function replace($Str){ 
   preg_match_all('/{(\w+)}/', $Str, $matches);
   $afterStr = $Str;
   foreach ($matches[0] as $index => $var_name) {
     if (isset(${$matches[1][$index]})) {
        $afterStr = str_replace($var_name, ${$matches[1][$index]}, $afterStr); 
     }
   }
     return $afterStr;
}

$value1 = 'Apple';
$value2 = 'Orange';

$text = 'The colors of {value1} and {value2} are different.';

echo replace($text);

以上代码给我的结果

{value1} 和 {value2} 的颜色不同。

但应该是这样的:

苹果和橙色的颜色不同。

你能告诉我我遗漏了什么以便我得到正确的结果吗?

提前致谢..

1 个答案:

答案 0 :(得分:1)

您的正则表达式有 {} 元字符。你不能按原样匹配它们。您可以使用反斜杠 \ 或使用 preg_quote() 对其进行转义。

您的代码非常冗长,带有循环。您可以传递值数组以替换为目标值数组,str_replace 可以很好地完成这项工作。

<?php

function replace($Str,$values = []){ 
   preg_match_all('/\{(\w+)\}/', $Str, $matches);
   return str_replace($matches[0],$values,$Str);
}

$value1 = 'Apple';
$value2 = 'Orange';

$text = 'The colors of {value1} and {value2} are different.';

echo replace($text,[$value1,$value2]);

您还没有将 $value1 和 $value2 传递给您的函数。如果有多个值要替换,我的建议是将它们传递到数组中。