【发布时间】:2018-03-18 13:30:50
【问题描述】:
我有一些预定义的单词,我想在一个句子中找到这些单词并添加一个 SPAN 标签。
例如;
Lorem Ipsum 只是打印和排版的虚拟文本 行业。 Lorem Ipsum 一直是业界标准的虚拟文本 自 1500 年代以来,当一位不知名的印刷商采用了一种类型的厨房和 争先恐后地制作了一本样书。
在这句话中,我想在单词中添加SPAM 标签:
单词:
- 行业标准
- 1500s
- 标本书
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);
【问题讨论】:
-
欢迎来到 StackOverflow!如果您遇到特定编程问题,我们很乐意为您提供帮助,但我们不是来为您编写代码或设计您的系统的。您至少需要尝试解决您自己的问题。请参阅How do I ask a good question? 和What topics can I ask about here?。
-
@AlexHowansky 我更新了我的问题。你真的很快发表评论:)
-
你在正确的轨道上。第一个提示——不要使用
preg_replace(),使用str_replace()。 -
您的代码运行良好,请查看@AlexHowansky 处理所有单词的建议。
-
@AlexHowansky 我用了这个
str_replace()但没有任何改变我看不到我的错误
标签: javascript php jquery html regex