我有一些预定义的单词,我想在句子中查找这些单词并添加 SPAN 标签。
例如;
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
在这句话中,我想为以下单词添加一个 SPAM
标签:
文字:
- 行业标准
- 1500秒
- 样本书
DOM
将是这样的
<div class="exampleArticle">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has
been the <span id="marked">industry's standard</span> dummy text ever since the <span id="marked">1500s</span>, when an unknown
printer took a galley of type and scrambled it to make a type <span id="marked">specimen book</span>.
</div>
代码:
$in = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.';
$words = array(
"industry's standard", "1500s", "specimen book"
);
$wrap_before = '<span id="marked">';
$wrap_after = '</span>';
$out = preg_replace("/($words)/i", "$wrap_before$1$wrap_after", $in);
最佳答案
当您不必使用正则表达式时,切勿使用正则表达式。 str_replace()
会很适合你。有很多方法可以得到你想要的东西。最明显的是每次替换调用一次 str_replace()
,不断更新相同的输出字符串:
$out = $in;
foreach ($words as $word) {
$out = str_replace($word, '<pre>' . $word . '<post>', $out);
}
如果您想变得更奇特,您可以利用 str_replace()
数组功能,一次性完成所有操作:
$out = str_replace(
$words,
array_map(function($word){ return '<pre>' . $word . '<post>'; }, $words),
$in
);
关于javascript - 查找 SPAN 并将其包裹在 DIV 中所有选定的单词周围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46610871/