php關鍵詞攔截程式,攔截後怎麼知道哪個詞為非法片語?
一、panduan.php
/**
* 判斷文本中是否存在關鍵詞
*/
function filter_text($text, $badstring){
$filter = explode('|', $badstring);
foreach ($filter as $key) {
if(strpos($text, $key) !== false){
return true;
}
}
return false;
}
?>
二、filter.php
$badstring="攔我|此內容|不允許";
?>
三、index.php
require_once("panduan.php");
require_once("filter.php");
$biaoti="如果包含此內容就不能通過!";
if(filter_text($biaoti, $badstring)){
echo "對不起,你提示的內容包含“$*****”文字不能表,請刪除“此內容”文字後再提交!";
exit();
}
?>
以上代碼能正確攔截事先設定好的關鍵詞,但怎麼寫才能提示是哪個關鍵詞非法的?如果取得引號中的內容:“$*****”?
請高手幫忙,謝謝!
------解決方案--------------------
在這裡修改成
if(strpos($text, $key) !== false){
return $key;
}
這裡
if(filter_text($biaoti, $badstring)){
echo "對不起,你提示的內容包含“$*****”文字不能表,請刪除“此內容”文字後再提交!";
exit();
}
修改成
$badstr=filter_text($biaoti, $badstring);
if($badstr){
echo "對不起,你提示的內容包含“.$badstr.”文字不能表,請刪除“此內容”文字後再提交!";
exit();
}
大約如此.
------解決方案--------------------
PHP code
$text = '攔我';$badstring = "/攔我|此內容|不允許/";if (preg_match($badstring, $text, $matchs)){ echo $matchs[0]; //var_dump($matchs);}
------解決方案--------------------
關於二者的效率
測試代碼:
PHP code
$start = microtime(true);$text = '攔我';$badstring = "/攔我|此內容|不允許/";$count = 0;for($i = 0; $i < 1000000; $i++) :if (preg_match($badstring, $text, $matchs)){ $count += 1;}endfor;$end = microtime(true);printf ("Complete Num: %d Total Time: %f sec (Using preg_match())", $count ,$end - $start);