2013-05-30 27 views
0

我有一段是在一個搜索功能,突出了關鍵詞代碼的亮點部分。相反,我希望能夠突出顯示關鍵字,即使它是文字的一部分。 例如,如果我搜索「EL」,並發現單詞「hello」,要顯示如H EL LO。PHP,關鍵字,而不是整個單詞

下面是代碼:

function highlight_keywords($content, $keywords) { 

    if (!is_array($keywords)) { 
    $keywords = explode(' ', $keywords); 
    } 
    foreach ($keywords as $keyword) { 
    if (trim($keyword) !== '') { 
     $content = preg_replace('/\b(' . preg_quote($keyword) . ')\b/i',  '<span>\1</span>', $content); 
    } 
    } 
    return $content; 
} 
+1

取出'\ B'字分隔符。 –

回答

0

試試這個:

$content = preg_replace('/(' . preg_quote($keyword) . ')/is','<span>$1</span>', $content); 
+0

太棒了!作品!非常感謝 ! – NickHoot

0

爲了方便,你可以只使用str_replace()

$keywords = array('el'); 
$string = 'hello world'; 

foreach($keywords as $keyword){ 
    $string = str_ireplace($keyword, '<b>' . $keyword . '</b>', $string); 
} 

// $string is now: h<b>el</b>lo world 
+0

如果字是用大寫字母將是唯一的問題,你用小寫字母 – lexmihaylov

+0

在這種情況下更換,只需要使用'str_ireplace()',不區分大小寫的版本。 –

+1

抱歉可能是我沒有解釋這一權利我的意思是,這回聲str_ireplace(「厄爾尼諾」,「 EL」,「HELLO」);這產生:H EL LO(你好) – lexmihaylov

相關問題