Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace several words in string using associative array keeping original case intact

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 do that with str_ireplace but then the matched words lose their case:

$glossary = array(
    'word1' => '<span title="Explanation for Word 1">word1</span>',
    'word2' => '<span title="Explanation for Word 2">word2</span>',
    'word3' => '<span title="Explanation for Word 3">word3</span>'
);

$text = "This is a text about Word1. We also talk about word2 and WORD3. Also woRd3, word2 and WORD1";

list($keys, $values) = array_divide($glossary);

$result = str_ireplace($keys, $values, $text);

As said, this works but in this solution all matching words will be in lowercase.

What I want to achieve is this:

'This is a text about <span title="Explanation for Word 1">Word1</span>. 
We also talk about <span title="Explanation for Word 2">word2</span> and
<span title="Explanation for Word 3">WORD3</span>.
Also <span title="Explanation for Word 3">woRd3</span>, 
<span title="Explanation for Word 2">word2</span>
and <span title="Explanation for Word 1">WORD1</span>'

Do the replacements and keep the case intact.

I found a great reply that came close but it only works with the addition of the span tag around the matched words, it does not add a second variable for the title (php str_ireplace without losing case).

I don't know enough regex (It dazzles me) to change it by adding a second variable for the span titles:

$txt = 'Hi! How are you doing? Have some stars: * * *!';
$array_of_words = array('Hi!', 'stars', '*');

$pattern = '#(?<=^|\W)(' 
       . implode('|', array_map('preg_quote', $array_of_words))
       . ')(?=$|\W)#i';

echo preg_replace($pattern, 
      "<span style='background-color:#EEEE00'>$1</span>", $txt);
like image 414
Klaaz Avatar asked Oct 20 '25 17:10

Klaaz


1 Answers

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;
like image 157
stepozer Avatar answered Oct 22 '25 07:10

stepozer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!