在DIV中的所有选定单词周围查找并包装SPAN

时间:2017-10-06 17:19:21

标签: javascript php jquery html regex

我有一些预定义的单词,我想在一个句子中找到这些单词并添加一个SPAN标记。

例如;

  

Lorem Ipsum只是打印和排版的虚拟文本   行业。 Lorem Ipsum一直是业界标准的虚拟文本   自16世纪以来,当一个未知的打印机采用了类型的厨房   把它拼凑成一本样本书。

在这句话中,我想在单词中添加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);

2 个答案:

答案 0 :(得分:1)

当您不必使用正则表达式时,切勿使用正则表达式。 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
);

答案 1 :(得分:0)

您需要将正则表达式模式(包括捕获组)放在数组的每个项目中。你现在拥有它的方式,你试图将一个数组注入一个字符串,这可能会产生一个“数组到字符串转换”错误。

$input = "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.";

$replaceText = array("/(industry's standard)/", "/(1500s)/", "/(specimen book)/");
$wrapBefore = '<span id="marked">';
$wrapAfter = '</span>';

$output = preg_replace($replaceText, "$wrapBefore$1$wrapAfter", $input);

echo $output;

我不是100%确定这是否是实现此目的的最有效方法,但它确实得到了你想要的东西(你可以自己添加外部<div>标签)

DEMO

或者,这是使用str_replace()array_walk()的版本(该想法归功于Alex)

$input = "Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s.. to make a type specimen book.";

$searchArray = array("industry's standard", "1500s", "specimen book");
$replacementArray = $searchArray;

$wrapBefore = '<span id="marked">';
$wrapAfter = '</span>';
array_walk($replacementArray, "addWrappers", array($wrapBefore, $wrapAfter));

$output = str_replace($searchArray, $replacementArray, stripslashes($input));

echo $output;

function addWrappers(&$searchTerm, $key, $additionalText)
{
    $searchTerm = $additionalText[0] . $searchTerm . $additionalText[1];
}

DEMO