简体   繁体   English

PHP 花括号替换多个值

[英]PHP curly braces replace multiple values

I want to place the value lara certain words in curly brackets.我想将值 lara 某些单词放在大括号中。 But it gives me $ str as a result.但它给了我 $ str 结果。 So it shows me the word the same without making any replacement.因此,它向我显示了相同的词,而没有进行任何替换。

I try it like follow:我尝试如下:

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);

The result that the above codes give me上述代码给我的结果

The colors of {value1} and {value2} are different. {value1} 和 {value2} 的 colors 不同。

But it should be like this:但它应该是这样的:

The colors of Apple and Orange are different. Apple 和 Orange 的 colors 不同。

Can you tell me what I am missing so that I can get the right result?你能告诉我我缺少什么以便我能得到正确的结果吗?

Thanks in advance..提前致谢..

You regex has { and } metacharacters.您的正则表达式具有{}元字符。 You can't match them as is.您无法按原样匹配它们。 You either escape it with backslash \ or use preg_quote() .你要么用反斜杠\转义它,要么使用preg_quote()

Your code is pretty verbose with loops.您的代码非常冗长,带有循环。 You can pass array of values to replace with array of destination values and str_replace does the job pretty nicely.您可以传递值数组以替换为目标值数组,而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]);

You also missed passing $value1 and $value2 to your function.您还错过了将 $value1 和 $value2 传递给 function。 My advice is to pass them in an array if there are multiple values to replace.如果要替换多个值,我的建议是在数组中传递它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM