突出显示搜索词

时间:2011-12-16 07:47:18

标签: php preg-replace

  

可能重复:
  Best way to parse HTML with PHP
  PHP Regular expression to match keyword outside HTML tag <a>

我想突出显示要搜索的关键字,并让替换HTML标记。我使用了这个函数,但它取代了链接(锚标签)。有没有办法突出显示搜索字词,而不会创建无效的HTML。

function highlightSearch($str,$keyword='')
{
    // $str=text in which I want to search,$keyword is the word which I want to replace.
    $keywords = preg_replace('/\s\s+/i', ' ', strip_tags(trim($keyword))); 
    foreach(array_unique(explode(' ', $keywords)) as $keyword)
    {
        //if(!preg_match("|<[^>]+>(.*)</[^>]+>|Ui",$str))
        $str = str_ireplace($keyword,"<b>".$keyword."</b>",$str);//preg_replace("|($keyword)|Ui", "<b>$1</b>", $str);
        //}
        //$str = str_ireplace( "<b>","<b>", $str);`
        return $str;
    }
}

0 个答案:

没有答案