Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace placeholders in array with values from other array

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 ?

like image 606
Alex Kneller Avatar asked Jul 30 '13 11:07

Alex Kneller


People also ask

What is the use of str_ replace in php?

The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array. If the string to be searched is an array, find and replace is performed with every array element.


1 Answers

foreach ($arr1 as $key => &$value) {
    $value = preg_replace_callback('/\{\{(.*?)\}\}/', function($match) use ($arr2) {
        return $arr2[$match[1]];
    }, $value);
}
like image 62
Barmar Avatar answered Oct 05 '22 22:10

Barmar