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 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);