I'm getting stuck at this problem, which is
I have an array like this:
$array = [
'name' => 'John',
'email' => john@gmail.com
];
And a string sample like this:
$string = 'Hi [[name]], your email is [[email]]';
The problem is obvious, replace name with John
and email with john@gmail.com
.
What i attempted:
//check if $string has [[ ]] pattern
$stringHasBrackets = preg_match_all('/\[\[(.*?)\]\]/i', $string, $matchOutput);
if ($stringHasBrackets) {
foreach ($matchOutput[1] as $matchOutputKey => $stringToBeReplaced) {
if (array_key_exists($stringToBeReplaced, $array)) {
$newString = preg_replace("/\[\[(.+?)\]\]/i",
$array[$stringToBeReplaced],
$string);
}
}
}
Which led me to a new string like this:
Hi john@gmail.com, your email is john@gmail.com
Makes sense because that's what the pattern is for, but not what I wanted.
How can I solve this? I thought of using a variable in the pattern but don't know how to do it. I've read about preg_replace_callback but also don't really know how to implement it.
Thanks!