I want to match an array against a text string where words matching with the array keys will be replaced by a span tag with a title with the matching array value.
I can
You can achieve it with some common PHP functions.
Create an array of patterns from your keys
to search in a case-insensitive manner with preg_replace_callback
.
Pass the $glossary
to the anonymous function in preg_replace_callback
and get the value (the <span>
title) by the lowercased current match value, and once found, replace the lowercase wordX
with the match.
This is PHP code:
$pttrns = array_map(function ($val) {return "/" . preg_quote($val) . "/i"; },
array_keys($glossary)); // Step 1
$res = preg_replace_callback($pttrns, function ($m) use($glossary){ // Step 2
return str_replace(strtolower($m[0]), $m[0],
$glossary[strtolower($m[0])]); // Step 3
}, $text);
You can run this replace in loop:
$txt = 'Hi! How are you doing? Have some stars: * * *!';
$glossary = array(
'Hi!' => 'title 1',
'stars' => 'title 2',
'*' => 'title 3'
);
$result = $txt;
foreach ($glossary as $keyword => $title) {
$pattern = '#(?<=^|\W)('.preg_quote($keyword).')(?=$|\W)#i';
$result = preg_replace($pattern, "<span title='{$title}'>$1</span>", $result);
}
echo $result;