Home > Backend Development > PHP Tutorial > 如何取得中文字符串中出现次数最多的子串_PHP

如何取得中文字符串中出现次数最多的子串_PHP

WBOY
Release: 2016-06-01 12:03:12
Original
804 people have browsed it

直接上代码,子串的长度可自己设置(比如连续4个字符的或5个字符的)。
复制代码 代码如下:
$str ='我是中国人我是外国人我是韩国人我是美国人我是中国人我是英国人我是中国人我是外国人';
Count_string($str,5);
function Count_string($sstr,$length)
{
 $cnt_tmp = 0;
 $cnt = 0;
 $str = '';
 $str_tmp = array();
 $str_arr = array();
 mb_internal_encoding("gb2312");
 $max_length = (mb_strlen($sstr)-$length);

 //取得子串集
 for($i=0;$i {
  $str_tmp[] =  mb_substr($sstr, $i, $length);
 }
 //去除重复子串
 $str_tmp = array_unique($str_tmp);

 //计算出现次数
 foreach($str_tmp as $key=>$value)
 {
  $cnt_tmp = mb_substr_count($sstr,$value);
  if($cnt_tmp>=$cnt)
  {
   $cnt = $cnt_tmp;
   $str_arr[$value] = $cnt;   
  }
 }

 //处理出现多重结果
 foreach($str_arr as $key=>$value)
 {
  if($value == $cnt)
  {$str .=$key."
";}
 }

 echo '出现最多的子串是:
'.$str.'
出现次数:'.$cnt;
}

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template