Replace placeholders in an array with values ​​from another array

I have 2 arrays with one 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 the placeholders with a value from arr2 ?

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

Of course, here is one way to do this. It takes a bit of 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 ); 
0
source

Source: https://habr.com/ru/post/950618/


All Articles