I need to get data from a string by a template. An example should make it clearer:
// What I have
$utterance = 'This is a brown bear with 7 kids';
$template = 'This is a {color} bear with {kids} kids';
// What I want
[
"color" => "brown",
"kids" => "7",
]
I have a very ugly solution to this:
$regex = '/' . preg_replace('/{.*?}/' , '.*?', $template) . '/i';
foreach(preg_split('/\{.*?\}/', $template) as $part) {
$utterance = str_replace($part, Str::startsWith($template, $part) || Str::endsWith($template, $part) ? '' : '|', $utterance);
}
preg_match_all('/{(.*?)}/', $template, $variables);
$values = explode('|', $utterance);
$variables = $variables[1];
array_combine($variables, $values);
Does anyone have a nicer way of doing this? Seems like an ugly approach...