正则表达式:去除非字母数字或标点符号 [英] Regex: Strip non alpha numeric or punctuation

查看:795
本文介绍了正则表达式:去除非字母数字或标点符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用PHP去除所有非字母,数字,空格或双引号的字符?

How can I use PHP to strip out all characters that are NOT alpha, numeric, space, or puncutation?

我尝试了以下方法,但是它删除了标点符号.

I've tried the following, but it strip punctuation.

preg_replace("/[^a-zA-Z0-9\s]/", "", $str);

推荐答案

preg_replace("/[^a-zA-Z0-9\s\p{P}]/", "", $str);

示例:

php > echo preg_replace("/[^a-zA-Z0-9\s\p{P}]/", "", "⟺f✆oo☃. ba⟗r!");
foo. bar!

\p{P}匹配所有Unicode标点字符(请参见Unicode 字符属性).如果只想允许特定的标点符号,只需将它们添加到否定的字符类中即可.例如:

\p{P} matches all Unicode punctuation characters (see Unicode character properties). If you only want to allow specific punctuation, simply add them to the negated character class. E.g:

preg_replace("/[^a-zA-Z0-9\s.?!]/", "", $str);

这篇关于正则表达式:去除非字母数字或标点符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆