如何在for
循环中将中文和英文字符分开?
这是代码:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
function filter_ch($char)
{
return $char;
}
function filter_en($char)
{
return $char;
}
$str='Hello 你怎么样? How are you?';
$english='';
$chinese='';
for ($i=0;$i<strlen($str);$i++)
{
$char = substr($str, $i, 1);
if(preg_match('/\p{Han}+/u', $char))
{//if chinese
$chinese.=filter_ch($char);
}
else
{//if english
$english.=filter_en($char);
}
}
echo 'chinese: '.$chinese.'<br>';
echo 'english: '.$english.'<br>';
?>
</body>
</html>
这是结果:
chinese:
english: english: Hello 你怎么样? How are you?
我想要的结果:
chinese: 你怎么样?
english: Hello How are you?