php關鍵詞攔截程式,攔截後如何知道哪個詞為非法片語

來源:互聯網
上載者:User
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); 
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.