我正在使用以下函數突出顯示從字符串搜索的關鍵字。它工作正常,但沒有什麼問題。只強調從字符串中鍵入的關鍵字在php
$text="This is simple test text";
$words="sim text";
echo highlight($text, $words);
使用下面的函數是突出兩個「簡單」 &「文本」的話,我想它應該突出「SIM」 &「文本」唯一的話。我需要做出什麼樣的改變才能達到這個結果。請指教。
function highlight($text, $words)
{
if (!is_array($words))
{
$words = preg_split('#\\W+#', $words, -1, PREG_SPLIT_NO_EMPTY);
}
$regex = '#\\b(\\w*(';
$sep = '';
foreach ($words as $word)
{
$regex .= $sep . preg_quote($word, '#');
$sep = '|';
}
$regex .= ')\\w*)\\b#i';
return preg_replace($regex, '<span class="SuccessMessage">\\1</span>', $text);
}
什麼是你用'\\ B','原因\\ w'和'\\ W'而不是'\ b','\ w'和'\ W'? – h2ooooooo
這兩種情況下都會得到相同的結果。請指教。 – KRA
@KRA,你想要什麼輸出準確的樣本輸入? – Dogbert