Rumah >pembangunan bahagian belakang >tutorial php >两个select查询结果,其中一个content(text),另一个是脏话词. 如何统计content在脏话词里面出现的次数.
完美的解决方法想不出来,毕竟还是渣渣。
想到一个比较丑的方法,看看就行:
$str = "1111111111111112b22222222caonima22222222"; $words = ['2b','caonima']; $res = []; foreach($words as $word){ $res[$word] = count(explode($word, $str))-1; } return $res;
如果说是只统计脏话次数,并不要求每一个脏话的次数,之前写过一个根据多个key切割字符串的函数
$str = "1111111111111112b22222222caonima22222222"; $words = ['2b','caonima']; function many_explode($cutKey,$string){ $return=[]; $key=0; for($i=0;$i<strlen($string);$i++){ if(in_array($string[$i], $cutKey)){ $key++; //当前字符在 cutKey 中,跳过,并另起一行 }else{ $return[$key]=isset($return[$key])?$return[$key].$string[$i]:$string[$i]; } } return $return; } return count(many_explode($words, $str)) -1;
换汤不换药
1,所有的脏话的关键词建立一个表.
2,内容context 做全文索引.
3,使用mysql自带的函数检索locate,或者你用like也可以.
$arr = array('2b', 'fuck'); $con = array( array( 'content'=>'asdfasdf2bsdfasdf2dfasdfuck' ), array( 'content'=>'asdfasdf2asdfasdf2dfasdfuck' ), array( 'content'=>'asdfasdfuckbsdfasdf2dfasdfuck' ), ); foreach($con as $ck => $cv) { foreach ($arr as $av) { if (($pos = strpos($cv['content'], $av)) !== false) { $cv['checkCount'][$av] = recursionSearch($cv['content'], $av, $pos, 1); } } $con[$ck] = $cv; } print_r($con); // function recursionSearch($haystack, $needle, $offset=0, $res=0 ) { $offset += strlen($needle); if (($pos = strpos($haystack, $needle, $offset)) === false) { return $res; } else { return recursionSearch($haystack, $needle, $pos, $res+1 ); } } // 打印结果 /** Array ( [0] => Array ( [content] => asdfasdf2bsdfasdf2dfasdfuck [checkCount] => Array ( [2b] => 1 [fuck] => 1 ) ) [1] => Array ( [content] => asdfasdf2asdfasdf2dfasdfuck [checkCount] => Array ( [fuck] => 1 ) ) [2] => Array ( [content] => asdfasdfuckbsdfasdf2dfasdfuck [checkCount] => Array ( [fuck] => 2 ) ) ) **/
谢谢回答合各位的回答,学习了多种写法。 用了qvga提供的第一种,后面加上array_sum统计了总数。 在次谢谢^_^