依赖scws,作为中文分词插件
/**
* 全角字符转变成半角字符
* @param $str
* @return mixed
*/
function replace_DBC2SBC($str) {
$DBC = Array(
'0' , '1' , '2' , '3' , '4' ,
'5' , '6' , '7' , '8' , '9' ,
'A' , 'B' , 'C' , 'D' , 'E' ,
'F' , 'G' , 'H' , 'I' , 'J' ,
'K' , 'L' , 'M' , 'N' , 'O' ,
'P' , 'Q' , 'R' , 'S' , 'T' ,
'U' , 'V' , 'W' , 'X' , 'Y' ,
'Z' , 'a' , 'b' , 'c' , 'd' ,
'e' , 'f' , 'g' , 'h' , 'i' ,
'j' , 'k' , 'l' , 'm' , 'n' ,
'o' , 'p' , 'q' , 'r' , 's' ,
't' , 'u' , 'v' , 'w' , 'x' ,
'y' , 'z' , '-' , ' ' , ':' ,
'。' , ',' , '/' , '%' , '#' ,
'!' , '@' , '&' , '(' , ')' ,
'<' , '>' , '"' , ''' , '?' ,
'[' , ']' , '{' , '}' , '\' ,
'|' , '+' , '=' , '_' , '^' ,
'¥' , ' ̄' , '`' , '“' , '”',
';' , '·'
);
$SBC = Array(
'0', '1', '2', '3', '4',
'5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E',
'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y',
'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x',
'y', 'z', '-', ' ', ':',
'.', ',', '/', '%', '#',
'!', '@', '&', '(', ')',
'<', '>', '"', '\'','?',
'[', ']', '{', '}', '\\',
'|', '+', '=', '_', '^',
'$', '~', '`', '"', '"',
';', '.'
);
return str_replace($DBC, $SBC, $str);
}
function hashCode($str) {
$str = (string)$str;
$hash = 0;
$len = strlen($str);
if ($len == 0 )
return $hash;
for ($i = 0; $i < $len; $i++) {
$h = $hash << 5;
$h -= $hash;
$h += ord($str[$i]);
$hash = $h;
$hash &= 0xFFFFFFFF;
}
return $hash;
}
function simHashCode($str){
return decbin(hashCode($str));
}
//采用scws分词
function simHash($text){
$so = scws_new();
$so->set_charset('utf8'); //编码
$so->set_duality(0); //散字二元
$so->set_ignore(0); //忽略标点符号
$so->set_multi(0);
$str = replace_DBC2SBC($text);
//过滤字符
$filter = [',','.','-','_','`','、','"',"'",":",';','<','>','{','}','(',')'];
$so->send_text($str);
$hash = [];
while($words = $so->get_result())
{
foreach($words as $word){
$s = $word['word'];
$weight = intval($word['idf']);
$hash_code = hashCode($s);
if(!in_array($s,$filter) && strlen($hash_code)>=6 && $weight){
$code = decbin($hash_code);
$code = str_repeat('0',32 - strlen($code)).$code;
for($i=1;$i<=32;$i++){
$value = intval($code[$i]);
if($value){
$hash[$i] += $weight;
}else{
$hash[$i] -= $weight;
}
}
}
}
}
for($i=1;$i<=32;$i++){
$hash[$i] = intval($hash[$i])>0 ? 1 : 0 ;
}
return implode('',$hash);
}
#使用
$sim_hash1 = simHash($content1);
$sim_hash2 = simHash($content3);
//levenshtein($sim_hash1,$sim_hash2); 用来计算两者之间的距离