2012年12月23日 星期日

[PHP] Highlight search result


一般我們在做搜尋時,輸出的結果都會對 keyword 做 highlight 來凸顯比對結果
像字串 How to highlight search result 如果以 highlight, result 為 keyword 來搜尋
我們一般期待輸出的結果為 How to <span class=highlight>highlight</span> search <span class=highlight>result</span>
如果單純以 str_replace 用迴圈來對每個 keyword 比對時,在跑第二次也會發生問題
或是用 array 來建立 keys 和 replace 也會有點麻煩

一個簡單的寫法是使用 preg_replace 來處理

以下是範例
<style>
    .highlight {color:red}
</style>
<?php
$keys[] = 'highlight';
$keys[] = 'result';
$text = 'How to highlight search result.';

echo findKeywords_org($text, $keys) . '<br>';
echo findKeywords($text, $keys) . '<br>';

function findKeywords_org($text, $keys)
{
$replace = array();
foreach($keys as $k)
{
$replace[] = "<span class=highlight>$k</span>";
}
return str_ireplace($keys, $replace, $text);
//這是 str_replace 不分大小寫的版本,但限定 php5 以上才有,故在 php4 要不分大寫法也須要自行處理,會很麻煩
}

function findKeywords($text, $keys)
{
    $text = htmlspecialchars($text);
    $patterns = '/('. implode('|', $keys) .')/i'; //i 是不分大小寫
    $replacements = '<span class=highlight>${0}</span>'; //${0}所以比對 patterns 到的字串 value
    return preg_replace($patterns, $replacements, $text);
}



Ref: http://php.net/manual/en/function.preg-replace.php

1 則留言:

  1. The casino that helped you find the golden age of online gambling
    The online gambling industry has become an incredibly rich one. While online 춘천 출장샵 gambling continues to 안양 출장샵 spread, many 성남 출장마사지 of the best 울산광역 출장안마 casino games, including 광양 출장샵

    回覆刪除