php可以过滤字符串,只显示字母和数字。实现方法:1、用“preg_match_all("/[a-zA-Z0-9]/u","$str",$arr)”查找字母和数字,将其存入数组中;2、用“join('',$arr[0])”将数组转为字符串。

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

php可以过滤字符串,只显示字母和数字。

在PHP中,可以利用preg_match_all()函数配合正则表达式来过滤字符串,只保留英文字母以及数字。

使用的正则表达式为:/[a-zA-Z0-9]/u

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

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

1.png

该数组是一个二维数组,可以使用join()函数将结果值拼接成一个字符串

join('',$arr[0])

2.png


php可以只显示字母和数字吗