方法:1、用“str_replace("指定符号","",$str)”去除指定符号;2、用“preg_match_all("/[\x{4e00}-\x{9fa5}a-zA-Z0-9]/u","$str",$result);”过滤掉全部符号。

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

php去掉字符串里的符号

方法1:使用str_replace()函数--去除指定符号

str_replace()函数可以搜索字符串中的指定符号,并将其替换为空字符

例如:去掉?符号

<?php
header("Content-type:text/html;charset=utf-8");
$str = "php.cn?php中文网。zblog,?#$%^&())*(&^";
$newstr=str_replace("?","",$str);
echo $newstr;
?>

1.png

方法2:使用preg_match_all()函数

preg_match_all()函数可以配合正则表达式来过滤字符串,只保留中文、英文以及数字,去掉其他全部符号

<?php
header("Content-type:text/html;charset=utf-8");
$str = "php.cn?php中文网。zblog,?#$%^&())*(&^";
preg_match_all("/[\x{4e00}-\x{9fa5}a-zA-Z0-9]/u","$str",$result);
var_dump($result);
?>

2.png

preg_match_all()函数接受一个数组类型的第三参数,用来存放所有匹配的结果。

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

echo join('',$result[0]);

3.png


php怎么去掉字符串里的符号