Last active
July 2, 2020 07:59
-
-
Save fagci/5c189856f00f4e3c4329858db19b5841 to your computer and use it in GitHub Desktop.
PHP function to render string path template using nested array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* PHP function to render string path template using nested array. | |
* Renders template string like "Nested array item value: {data.some.nested.item.value}" | |
* @param string $template | |
* @param array $data | |
* @return string | |
*/ | |
public static function renderDataTemplate(string $template, array $data): string | |
{ | |
return preg_replace_callback('/{([^{}]+?)}/', static function ($v) use ($data) { | |
$temp = &$data; | |
foreach (explode('.', $v[1]) as $key) { | |
$temp = &$temp[$key] ?? null; | |
if ($temp === null) { | |
return null; | |
} | |
} | |
return $temp; | |
}, $template); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment