包含特殊字符的任何英文ASCII字符的正则表达式 [英] Regex for Any English ASCII Character Including Special Characters
本文介绍了包含特殊字符的任何英文ASCII字符的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用php写一个正则表达式,使其仅匹配任何英文字符,空格,数字和所有特殊字符.
I want to write a regex in php to match only any english characters, spaces, numbers and all special chars.
从这个问题 对任意ascii字符进行正则
我尝试过
preg_match("/[\x00-\x7F]+/", $str);
但它会发出警告
No ending delimiter '/' found
因此,如何在php中编写此正则表达式.
so, how to write this regex in php.
替代方法可能像[a-z \ d \ s]这样,也可以一一考虑所有特殊字符,但是没有办法做得更简单吗?
the alternative would be smth like [a-z\d\s] and also one by one consider all special chars, but is not there a way to do simpler ?
谢谢
推荐答案
有许多复杂的解决方案,但我建议使用这种非常简单的正则表达式:
There are a number of intricate solutions, but I would suggest this beautifully simple regex:
^[ -~]+$
它允许 ASCII表中的所有可打印字符.
It allows all printable characters in the ASCII table.
在PHP中:
$regex = '%^[ -~]+$%';
if (preg_match($regex, $yourstring, $m)) {
$thematch = $m[0];
}
else { // no match...
}
说明
-
^
锚断言我们在字符串的开头 - 字符类
[ -~]
匹配空格和波浪号之间的所有字符(ASCII表中的所有可打印字符) -
+
量词的意思是匹配其中一个或多个" -
$
锚断言我们在字符串的末尾
- The
^
anchor asserts that we are at the beginning of the string - The character class
[ -~]
matches all characters between the space and the tilde (all the printable characters in the ASCII table) - The
+
quantifier means "match one or more of those" - The
$
anchor asserts that we are at the end of the string
这篇关于包含特殊字符的任何英文ASCII字符的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文