Home > Backend Development > PHP Tutorial > How to get the substring with the most occurrences in a Chinese string_PHP Tutorial

How to get the substring with the most occurrences in a Chinese string_PHP Tutorial

WBOY
Release: 2016-07-21 14:59:33
Original
859 people have browsed it

Enter the code directly, and the length of the substring can be set by yourself (for example, 4 consecutive characters or 5 characters).

Copy code The code is as follows:

$str ='I am Chinese I am foreigner I am Korean I am American, I am Chinese, I am British, I am Chinese, I am foreigner';
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);

//Get the substring set
for($i=0;$i<=$max_length;$i++ )
{
$str_tmp[] = mb_substr($sstr, $i, $length);
}
//Remove duplicate substrings
$str_tmp = array_unique($str_tmp);

//Calculate the number of occurrences
foreach($str_tmp as $key=>$value)
{
$cnt_tmp = mb_substr_count($sstr,$value);
if ($cnt_tmp>=$cnt)
{
$cnt = $cnt_tmp;
$str_arr[$value] = $cnt;
}
}

// Handling multiple results
foreach($str_arr as $key=>$value)
{
if($value == $cnt)
{$str .=$key."< br>";}
}

echo 'The most frequently occurring substring is:
'.$str.'
Number of occurrences:'.$cnt;
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/328134.htmlTechArticleAdd the code directly, and the length of the substring can be set by yourself (such as 4 consecutive characters or 5 characters) . Copy the code. The code is as follows: $str ='I am Chinese, I am a foreigner, I am Korean, I am American...
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