javascript - 查找 SPAN 并将其包裹在 DIV 中所有选定的单词周围

标签 javascript php jquery html regex

我有一些预定义的单词,我想在句子中查找这些单词并添加 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/

相关文章:

javascript - GWT 可视化核心图表包和 SmartGWT 的问题

php - FairCom c-tree ODBC 连接 - PHP

php - 如何使用 JQuery AJAX 发送图像和文本

php - 将大 xls 文件导入 mysql 数据库

javascript - 如何为这个 jQuery 代码定义 if 语句?

javascript - 当实际结束时播放列表中的下一个 YouTube 视频

javascript - 在外部作用域中使用 let 或 const 声明变量之前,在闭包中使用变量是否合法?

javascript - JQuery animate 完整功能未运行

JQuery 仅在按钮单击时验证,而不在模糊/onchange 时验证

javascript - innerHTML 返回带有文本的 NaN