简体   繁体   English

用其他数组中的值替换数组中的占位符

[英]Replace placeholders in array with values from other array

I have 2 arrays one with placeholder that are keys in another array我有 2 个带有占位符的数组,它们是另一个数组中的键

arr1 = array(
    "id"       => "{{verticalId}}",
    "itemPath" => "{{verticalId}}/{{pathId}}/");

arr2 = array(
        "verticalId" => "value1",
        "pathId"     => "value2");

So how can I run on arr1 and replace placeholders with value from arr2 ?那么如何在arr1运行并用来自arr2值替换占位符?

foreach ($arr1 as $key => &$value) {
    $value = preg_replace_callback('/\{\{(.*?)\}\}/', function($match) use ($arr2) {
        return $arr2[$match[1]];
    }, $value);
}

Sure, here's one way to do it. 当然,这是一种方法。 It needs a little love though, and PHP 5.3+ 它需要一点爱,PHP 5.3+

<?php
$subject = array(
    'id' => '{{product-id}}'
);

$values = array(
    'product-id' => 1
);

array_walk($subject, function( & $item) use ($values) {
    foreach($values as $template => $value) {
        $item = str_replace(
            sprintf('{{%s}}', $template),
            $value,
            $item
        );
    }
});

var_dump(
    $subject
);
  • It is not (and was not back in 2013) necessary to loop the target array in @Barmar's answer.在@Barmar 的答案中循环目标数组不是(并且在 2013 年也没有)。 An array is allowed as the $subject of to the preg_replace_callback() function.数组被允许作为preg_replace_callback()函数的 $subject 。

  • You can as of PHP 7.4 use the arrow function form which has access to the parent scope automatically.从 PHP 7.4 开始,您可以使用可以自动访问父作用域的箭头函数形式。

  • You do not need to escape curly brackets in the pattern.您不需要转义模式中的大括号。 The last opening bracket would only need to be escaped if the bracket contents are an exact number, like {\\{300}}如果括号内容是确切的数字,则只需要转义最后一个左括号,例如{\\{300}}

  • I generally don't advise .* in regular expressions, but I would just come up with a rule that characters inside {{ }} are only allowed to be \\w+我通常不建议在正则表达式中使用.* ,但我只是想出了一个规则,即{{ }}中的字符只能是\\w+

Latest answer:最新回答:

$arr1 = preg_replace('/{{\w+}}/', fn($m) => $arr2[$m[1]], $arr1);

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

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