?>
查询字符串在数组中出现的次数
<?php $array = array(1, "hello", 1, "world", "hello","11"); //计算$string在$array(需为数组)中重复出现的次数 function get_array_repeats(array $array,$string) { $count = array_count_values($array); //统计中重复元素的次数,再重组数组, //打印array_count_values($array)出,结果: //Array( // [1] => 2 // [hello] => 2 // [world] => 1 //) if (key_exists($string,$count)){ return $count[$string]; }else{ return 0; } } $string="11"; echo get_array_repeats($array,$string); ?>
查询字符在字符串中出现的次数
<?php $colors= array('red','blue','green','yellow','red'); $str = implode(',',$colors); $count=substr_count($str,'red'); echo $count; ?>