如何使用标记替换字符串中的数组匹配以突出显示,但从不重叠标记?
问题描述:
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,
如果我的字符串是: p>
一夜之间沉闷 ,
当我思索,疲惫和疲惫,
许多古怪和好奇的遗忘的知识卷,
code> pre>
我想要突出显示以下字符串(排序依据 字符串长度更喜欢更长的字符串匹配): p>
思考,厌倦,弱,ary,红色,我们
code> pre>
我想最终得到: p>
一夜午dre&lt; span&gt; ary&lt; / span&gt;,
而我&lt; span&gt; ponder&lt; / span&gt; ed, &LT;跨度&GT;弱&LT; /跨度&GT; 和&lt; span&gt;疲倦&lt; / span&gt;,
许多古怪和奇怪的遗忘量,
code> pre>
我如何避免(作为一个简单的 str_replace() code>可能会引导我)? p>
一夜午dre&lt; span&gt; ary&lt; / span&gt;,
而我&lt; span&gt; ponde&lt; span&gt; r&lt; / span&gt; ed&lt; / span&gt;,&lt; span&gt;&lt; span&gt; we&lt; / span&gt; ak&lt; / span&gt; 和&lt; span&gt;&lt; span&gt;我们&lt; / span&gt;&lt; span&gt; ary&lt; / span&gt;&lt; / span&gt;,
许多古怪和好奇的遗忘传说,
code> pre >
div>
答
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.