I am trying to loop through the result of preg_match_all() and to replace the matches.
What I am trying to achieve is to extract all the occurrences in a text that is in between curly brackets with a dollar sign in front, and then create a <span> with an id that is the content within the curly brackets.
So in the example below from the text "Working from ${spa_open_time} to ${spa_close_time} every day", I should extract ${spa_open_time} and ${spa_close_time} and replace them in the text with a <span>.
The expected result
Working from <span id="tag_spa_open_time">${spa_open_time}</span> to <span id="tag_spa_close_time">${spa_close_time}</span> every day
Here is the code I came up with so far
$text = 'Working from ${spa_open_time} to ${spa_close_time} every day';
$result = preg_match_all('/(\$\{\w+\})/', $text, $positive_catch);
if ($result > 0) {
foreach ($positive_catch as $catch) {
if (is_array($catch)) {
foreach ($catch as $key => $ivalue) {
$fvalue = str_replace("\${", "", $ivalue);
$fvalue = str_replace("}", "", $fvalue);
$replace = '<span id="tag_'.$fvalue.'">'.$ivalue.'</span>';
$str = str_replace($catch,$replace,$text);
}
}
}
} else {
$str = $text;
}
echo $str;
And the current result is
Working from <span id="tag_spa_close_time"><span id="tag_spa_close_time">${spa_close_time}</span></span> to <span id="tag_spa_close_time">${spa_close_time}</span> every day
I am doing something wrong but I cannot figure out what's the problem. Here is the code in action http://sandbox.onlinephpfunctions.com/code/31894399fd981fb791c587fa04c68581c4945b6d