php中可用preg_match_all()配合正则表达式过滤字符串,只获取中文字符;语法“preg_match_all("/[\x{4e00}-\x{9fff}]+/u","$str",$arr);”,会将匹配字符存入“$arr”数组中。

本教程操作环境:windows7系统、PHP7.1版、DELL G3电脑

在php中,可以使用preg_match_all()函数来只获取中文字符。

preg_match_all()函数会搜索字符串中所有可以和正则表达式匹配的结果

preg_match_all()函数配合正则表达式“/[\x{4e00}-\x{9fff}]+/u”可以过滤字符串,只获取中文字符。

会将匹配的中文字符一个个存入数组中(该数组由第三个参数指定)。

<?php
header("Content-type:text/html;charset=utf-8");
$str = "欢迎4546来到php这里。zblog,我的?#$%^天呀&())*(&^";
echo $str;
preg_match_all("/[\x{4e00}-\x{9fff}]+/u","$str",$arr);
var_dump($arr);
?>

1.png

然后可以使用join()函数将结果值拼接成一个字符串。

<?php
header("Content-type:text/html;charset=utf-8");
$str = "欢迎4546来到php这里。zblog,我的?#$%^天呀&())*(&^";
echo $str;
preg_match_all("/[\x{4e00}-\x{9fff}]+/u","$str",$arr);
var_dump($arr);
echo join('',$arr[0]);
?>

2.png


php怎么只获取中文字符