Replace placeholders in array with values from other array
Asked Answered
U

3

6

I have 2 arrays one with placeholder that are keys in another array

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 ?

Unplaced answered 30/7, 2013 at 11:54 Comment(0)
X
5
foreach ($arr1 as $key => &$value) {
    $value = preg_replace_callback('/\{\{(.*?)\}\}/', function($match) use ($arr2) {
        return $arr2[$match[1]];
    }, $value);
}
Xenon answered 30/7, 2013 at 11:58 Comment(0)
R
0

Sure, here's one way to do it. It needs a little love though, and 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
);
Roldan answered 30/7, 2013 at 12:0 Comment(0)
L
0
  • It is not (and was not back in 2013) necessary to loop the target array in @Barmar's answer. An array is allowed as the $subject of to the preg_replace_callback() function.

  • You can as of PHP 7.4 use the arrow function form which has access to the parent scope automatically.

  • 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}}

  • 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+

Latest answer:

$arr1 = preg_replace('/{{\w+}}/', fn($m) => $arr2[$m[1]], $arr1);
Lepage answered 15/10, 2021 at 22:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.