判断提取一个字符串中英文字母和中文字符(一)
判断提取一个字符串中英文字母和中文字符的长度
通过这个函数,你可以提取任意一个字符串中的英文字母(标点)和中文字符(标点)及其长度:
[coolcode lang=”php”‘]
function splitStr($str)
{
$len = strlen ($str);
$i = 0;
$output = array();
while ($i<$len)
{
if (preg_match("/^[".chr(0xa1)."-".chr(0xff)."]+$/",$str[$i]))
{
$output['cn'][] .= $str[$i].$str[$i+1];
$i += 2;
}
else
{
$output['en'][] .= $str[$i];
$i += 1;
}
}
if(count($output['cn'])==0 AND count($output['en'])==0){
$output['count'] = 0;
}
else if(count($output['cn'])==0 OR count($output['en'])==0){
$output['count']= count($output, COUNT_RECURSIVE)-1;
}
else{
$output['count']= count($output, COUNT_RECURSIVE)-2;
}
return $output;
}
$str="1234你好56";
$str = splitStr($str);
print_r($str);
?>
[/coolcode]
函数返回一个数组$output,其中$output[‘cn’]中存储的是中文字符,$output[‘en’]存储的是英文字符,$output[‘count’]存储的是字符个数.
注:chr(0xa1)-chr(0xff)是汉字的ASCII码范围.