2013-03-16 30 views
0

我有這個突出顯示關鍵字的函數。它工作的很好,但它似乎不適用於單引號和雙引號。如何在突出顯示關鍵字的函數中支持引號

function highlight($input, $keywords) { 

    // Hello Mr Regex 
    preg_match_all('~\w+~', $keywords, $match); 

    // If there's no match 
    if(!$match) { return $input; } 

    // Case sensitive search 
    //$result = '~\\b(' . implode('|', $match[0]) . ')\\b~'; 

    // Case insenstive search 
    $result = '~\\b(' . implode('|', $match[0]) . ')\\b~i'; 

    // Return highlighted text 
    return preg_replace($result, '<strong>$0</strong>', $input); 

} 

$keywords = "just another what's little's test";

$input = "here what what's just looking little's another's this's for another one that requires a test";


結果:這裏什麼什麼的只是尋找一點是另一個人的另一個一個需要測試


在這個例子中,它不應該被突出這是


我使用htmlspecialchars()也嘗試兩個輸入和關鍵字,但這似乎也沒有得到匹配。

任何想法?

回答

2

\w只是字母,數字和下劃線。如果你想包含引號或撇號,你可以創建一個字符類:

preg_match_all('~[\w\'"]+~' ... 
+0

完美,謝謝! – 2013-03-16 19:17:49

+0

你能推薦學習正則表達式的好資源嗎? – 2013-03-16 19:18:05

+2

@Titanium http://www.regular-expressions.info/似乎是每個人的最愛 – 2013-03-16 19:19:03

相關問題