PHP中英文字符长度判断
$content = $_POST['content'];
$type = judgeEnCn($content);
if (!$type) {
$data = array('state' => 200, 'msg' => '推荐内容不能超过600字或200个单词');
echo json_encode($data);die;
}
function judgeEnCn($str)
{
if (empty($str)) return false;
$language = self::EnglishOrChinese($str);
switch ($language) {
case 'ENGLISH':
$str = str_replace(' ', ' ', $str);
$arr = explode(' ', $str);
$arr = array_filter($arr);
$arrLength = count($arr);
if ($arrLength > 200) {
return false;
}
break;
default:
if (mb_strlen($str) > 600) {
return false;
}
break;
}
return true;
}
private function EnglishOrChinese($str)
{
$mb = mb_strlen($str, 'utf-8');
$st = strlen($str);
if ($st == $mb)
return 'ENGLISH';
if ($st % $mb == 0 && $st % 3 == 0) {
return 'CHINESE';
} else {
return 'MIXTURE';
}
}
EnglishOrChinese() 方法借鉴了:https://blog.csdn.net/carrousel0516/article/details/90229209
|