First create a new array with your search fields, wrapped in curly braces:
$searchArray = array_map(function($value) {
return "{{" . $value . "}}";
}, array_keys($array));
Now you have an array with the tokens you are searching for, and you already have an array of values you want to replace the tokens with.
So just do a simple str_replace:
echo str_replace($searchArray, $array, $str);
Working example: https://3v4l.org/8tPZt
Here's a tidy little function put together:
function fillTemplate($templateString, array $searchReplaceArray) {
return str_replace(
array_map(function($value) { return "{{" . $value . "}}"; }, array_keys($searchReplaceArray)),
$searchReplaceArray,
$templateString
);
}
Now you can call it like this:
echo fillTemplate(
"Hello {{name}} welcome to {{company_name}}",
['name' => 'max', 'company_name' => 'Stack Exchange']
);
// Hello max welcome to Stack Exchange
Example: https://3v4l.org/rh0KX
echo 'Hello'.$name.', Welcome to '.$company;