簡體   English   中英

在DIV中查找並包裝所有選定單詞周圍的SPAN

[英]Find and wrap SPAN around all selected words in a DIV

我有一些預定義的單詞,我想在句子中找到這些單詞並添加一個SPAN標簽。

例如;

Lorem Ipsum只是印刷和排版行業的偽文本。 自1500年代以來,Lorem Ipsum一直是行業的標准偽文本,當時一位不知名的打印機拿起一個廚房,將其打亂成一本樣本書。

我想在這句話中添加一個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
);

您需要將正則表達式模式(包括捕獲組)放在數組的每個項目中。 現在,您正在嘗試將數組注入字符串,這很可能會產生“數組到字符串轉換”錯誤。

$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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM