Open gitzwt opened 3 years ago
目前只提供了检测功能,检测结果提供了位置和词的长度,直接替换就行了!
我今天搞了一个
/**
* 检测内容违规信息
* @param string $content
* @param int $timeout
* @return array
*/
public static function checkWordsMatch(string $content, $timeout = 3): array
{
try {
return WMServer::getInstance()->detect($content, $timeout);
} catch (\Throwable $e) {
return [];
}
}
/**
* 将违规内容替换
* @param string $content
* @param string $repeat
* @return string
*/
public static function repeatWordsMatch(string $content, string $repeat = '*'): string
{
$result = self::checkWordsMatch($content);
foreach ($result as $res){
$location = $res->getLocation()[0];
$len = $location['length'];
$rep = str_repeat($repeat, $len);
foreach ($location['location'] as $start){
$content = mb_substr_replace($content, $rep, $start , $len);
}
}
return $content;
}
得在bootstrap放上这个函数
if (function_exists('mb_substr_replace') === false) {
/**
* @param $string
* @param $replacement
* @param $start
* @param null $length
* @param null $encoding
* @return string
*/
function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = null): string
{
$string_length = (is_null($encoding) === true) ? mb_strlen($string) : mb_strlen($string, $encoding);
if ($start < 0) {
$start = max(0, $string_length + $start);
} else if ($start > $string_length) {
$start = $string_length;
}
if ($length < 0) {
$length = max(0, $string_length - $start + $length);
} else if ((is_null($length) === true) || ($length > $string_length)) {
$length = $string_length;
}
if (($start + $length) > $string_length) {
$length = $string_length - $start;
}
if (is_null($encoding) === true) {
return mb_substr($string, 0, $start) . $replacement . mb_substr($string, $start + $length, $string_length - $start - $length);
}
return mb_substr($string, 0, $start, $encoding) . $replacement . mb_substr($string, $start + $length, $string_length - $start - $length, $encoding);
}
}
可否添加下词替换方法,检测到词后替换成*或自定义字符