How can I replace array matches within a string with tags to highlight, but never overlap tags?

StackOverflow https://stackoverflow.com/questions/23093449

  •  04-07-2023
  •  | 
  •  

سؤال

If my string is:

Once upon a midnight dreary,
while I pondered, weak and weary,
Over many a quaint and curious volume of forgotten lore,

And I wanted to highlight the following strings (sorted by string length to prefer longer string matches) :

ponder,weary,weak,ary,red,we

I want to end up with:

Once upon a midnight dre<span>ary</span>,
while I <span>ponder</span>ed, <span>weak</span> and <span>weary</span>,
Over many a quaint and curious volume of forgotten lore,

How can I avoid (as a simple str_replace() might lead me)?

Once upon a midnight dre<span>ary</span>,
while I <span>ponde<span>r</span>ed</span>, <span><span>we</span>ak</span> and <span><span>we</span><span>ary</span></span>,
Over many a quaint and curious volume of forgotten lore,
هل كانت مفيدة؟

المحلول

Use word boundaries:

$s = <<< EOF
Once upon a midnight dreary,
while I pondered, weak and weary,
Over many a quaint and curious volume of forgotten lore,
EOF;
echo preg_replace('/(^|\s)(weary|weak|we|ary)\b/i', '$1<span>$2</span>', $s);

OUTPUT:

Once upon a midnight dreary,
while I pondered, <span>weak</span> and <span>weary</span>,
Over many a quaint and curious volume of forgotten lore,

نصائح أخرى

A possible solution would be to break the string up by spaces so you have all the words. You could then do your search and replace on each word and but the words back together as a sentence.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top