[英]highlight only typed keywords from string in 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);
}
為此,您需要將所有相關文本捕獲到組中。
完整代碼:(我已標記已更改的行。)
$text="This is simple test text";
$words="sim text";
echo highlight($text, $words);
function highlight($text, $words)
{
if (!is_array($words))
{
$words = preg_split('#\\W+#', $words, -1, PREG_SPLIT_NO_EMPTY);
}
# Added capture for text before the match.
$regex = '#\\b(\\w*)(';
$sep = '';
foreach ($words as $word)
{
$regex .= $sep . preg_quote($word, '#');
$sep = '|';
}
# Added capture for text after the match.
$regex .= ')(\\w*)\\b#i';
# Using \1 \2 \3 at relevant places.
return preg_replace($regex, '\\1<span class="SuccessMessage">\\2</span>\\3', $text);
}
輸出:
This is <span class="SuccessMessage">sim</span>ple test <span class="SuccessMessage">text</span>
嗨,不要使用php突出顯示搜索詞,它需要花費一些時間才能找到並替換每個詞。
使用jquery會比php容易。
簡單的例子:
function highlight(word, element) {
var rgxp = new RegExp(word, 'g');
var repl = '<span class="yourClass">' + word + '</span>';
element.innerHTML = element.innerHTML.replace(rgxp, repl); }
highlight('dolor');
希望對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.