方式一文章来源:https://www.toymoban.com/news/detail-405843.html
<?php
/**
* 敏感词过滤
*
* @param string
* @return string
*/
function sensitive_words_filter($str)
{
if (!$str) return '';
$file = 'public/system/plug/censorwords/CensorWords'; //文件路径及内容自定义
$words = file($file);
foreach ($words as $word) {
$word = str_replace(array("\r\n", "\r", "\n", "/", "<", ">", "=", " "), '', $word);
if (!$word) continue;
$ret = preg_match("/$word/", $str, $match);
if ($ret) {
return $match[0];
}
}
return '';
}
二 同思路
创建 敏感词.csv文章来源地址https://www.toymoban.com/news/detail-405843.html
// 敏感词过滤
$result = $this->get_Sensitive_Words_csv($params['post_content']);
if($result == true){
return reply("包含敏感字",1,$validator->errors());
}
function get_Sensitive_Words_csv($content=''){
// $csv_file='精确敏感词.csv';
$csv_file='/www/wwwroot/mg.csv'; // 不能中文文件名
// 防止乱码
$content = '';
$text = file_get_contents($csv_file);
//$encodType = mb_detect_encoding($text);
define('UTF32_BIG_ENDIAN_BOM', chr(0x00) . chr(0x00) . chr(0xFE) . chr(0xFF));
define('UTF32_LITTLE_ENDIAN_BOM', chr(0xFF) . chr(0xFE) . chr(0x00) . chr(0x00));
define('UTF16_BIG_ENDIAN_BOM', chr(0xFE) . chr(0xFF));
define('UTF16_LITTLE_ENDIAN_BOM', chr(0xFF) . chr(0xFE));
define('UTF8_BOM', chr(0xEF) . chr(0xBB) . chr(0xBF));
$first2 = substr($text, 0, 2);
$first3 = substr($text, 0, 3);
$first4 = substr($text, 0, 3);
$encodType = "";
if (UTF8_BOM == $first3) {
$encodType = 'UTF-8 BOM';
} else if (UTF32_BIG_ENDIAN_BOM == $first4) {
$encodType = 'UTF-32BE';
} else if (UTF32_LITTLE_ENDIAN_BOM == $first4) {
$encodType = 'UTF-32LE';
} else if (UTF16_BIG_ENDIAN_BOM == $first2) {
$encodType = 'UTF-16BE';
} else if (UTF16_LITTLE_ENDIAN_BOM == $first2) {
$encodType = 'UTF-16LE';
}
//下面的判断主要还是判断ANSI编码的·
if ('' == $encodType) {
//即默认创建的txt文本-ANSI编码的
$content = iconv("GBK", "UTF-8", $text);
} else if ('UTF-8 BOM' == $encodType) {
//本来就是UTF-8不用转换
$content = $text;
} else {
//其他的格式都转化为UTF-8就可以了
$content = iconv($encodType, "UTF-8", $text);
}
$arr = explode("\r\n",$content);
//读取文件
// $file=file_get_contents($csv_file);
// $arr = explode("\r\n",$file);
foreach($arr as $k=>$v){
if($v){
if(strpos($content,trim($v))!==false){ // 有敏感字
return true;
}
}
}
return false;
}
到了这里,关于PHP之 敏感词过滤的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!