使用 PHP 標記多個關鍵字
  • 4,726 views,
  • 2013-09-03,
  • 上傳者: Kuann Hung,
  •  0
2264bf3fb63a219d674a6463cadb98dd.png
 

一般說來,如果要做搜尋,通常都會把關鍵字標記起來。不過如果做多個關鍵字查詢時,還要把文章中出現多個字也標記就會比較麻煩了。

例如,要把 font color 標記起來,如果原文是 The font color is red。若你單純的 replace 兩次,標記紅色字,就會變成

第一次 replace font

The <font color='red'>font</font> color is red

第二次 replace color

The <font <font color='red'>color</font>='red'>font</font> <font color='red'>color</font> is red

這樣就會亂掉了。研究了一下,直接給大家看我的作法,如果有更好的建議歡迎提出喔!

function MarkKeywords($text, $keys)
{
    $text = htmlspecialchars($text);
     
    $patterns = '/('. implode('|', $keys) .')/i';
    $ntext = preg_replace_callback(
            $patterns,
            create_function(
                '$matches',
                'return "<font color=\"red\">$matches[0]</font>";'
            ),
            $text
        );
 
    return $ntext;
}
 

使用方式如下:

$text = "The font color is red";
 
$keys[] = 'font';
$keys[] = 'color';
 
$marked = MarkKeywords($text, $keys);
 
echo $marked;
 

這樣一來,不但不分大小寫,而且不會處理錯誤!提供給大家囉!

* 有朋友提出更好的做法。也 PO 在下面喔!如果不對比對的文字另外處理的話,以下的作法就可以達到要求了!

function MarkKeywords($text, $keys)
{
    $text = htmlspecialchars($text);
    $patterns = '/('. implode('|', $keys) .')/i';
    $replacements = '<font color=red>${0}</font>';
    return preg_replace($patterns, $replacements, $text);
}
Facebook 討論區載入中...
資料夾 :
標籤 :
發表時間 :
2013-09-03 17:25:37
觀看數 :
4,726
發表人 :
Kuann Hung
部門 :
老洪的 IT 學習系統
QR Code :