关于正则表达式的问题
我看到这个说法
$name = ereg_replace("[^A-Za-z0-9.]", "", $name);
[^A-Za-z0-9.]
和 [A-Za-z0-9.]
有什么区别?
根据我对正则表达式的理解,[]
用于包含函数ereg_replace
中替换的所有有效字符。
那么[]
中包含^
的目的是什么呢?
谢谢
I saw this statement
$name = ereg_replace("[^A-Za-z0-9.]", "", $name);
What is the difference between [^A-Za-z0-9.]
and [A-Za-z0-9.]
?
Based on my understanding of regular expression, the []
is used to include all valid characters for replacment in function ereg_replace
.
Then what is the purpose of including ^
into the []
?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
字符类
[…]
中的初始^
反转字符类中描述的字符集。[A-Za-z0-9.]
匹配A-Za-z0-9.
描述的字符集中的一个字符,[^A- Za-z0-9.]
匹配除A-Za-z0-9.
描述的字符之一之外的任何其他字符。这些其他字符是什么取决于定义字符串的基本字符集。因此
[abc]
匹配a
、b
或c
和[^abc] 匹配除
a
、b
和c
之外的任何其他字符。您的示例代码将删除[A-Za-z0-9.]
未描述的任何字符。这样就只剩下[A-Za-z0-9.]
字符。The initial
^
inside a character class[…]
inverts the set of characters that are described inside the character class. While[A-Za-z0-9.]
matches one character of the character set described byA-Za-z0-9.
,[^A-Za-z0-9.]
matches any other character except one of the characters described byA-Za-z0-9.
. What these other characters are depends on the base character set the string is defined with.So
[abc]
matches eithera
,b
, orc
and[^abc]
matches any other character excepta
,b
, andc
. Your example code will remove any characters that are not described by[A-Za-z0-9.]
. That leaves only characters of[A-Za-z0-9.]
.