Home > Article > Backend Development > There are two select query results, one of which is content (text) and the other is a swear word. How to count the number of times content appears in a swear word.
I can’t think of a perfect solution, it’s still rubbish after all.
I thought of an ugly method, just take a look:
$str = "1111111111111112b22222222caonima22222222"; $words = ['2b','caonima']; $res = []; foreach($words as $word){ $res[$word] = count(explode($word, $str))-1; } return $res;
If you only count the number of swear words, and do not require the number of each swear word, I have previously written a function that cuts strings based on multiple keys
$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;
Change the soup without changing the medicine
1. Create a table with all the keywords of swear words.
2. Use the content context as a full-text index.
3. Use the function that comes with mysql to search locate, or you can use 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 ) ) ) **/
Thank you for your answers. I have learned a variety of writing methods. I used the first one provided by qvga, and then added array_sum to count the total. Thank you ^_^