完美的解決方法想不出來,畢竟還是渣渣。
想到一個比較醜的方法,看看就行:
$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統計了總數。 在次謝謝^_^