preg_replace 函数中模式参数的 # 和 / 之间的区别?
# 符号与 / 的作用有何不同?
$output = preg_replace('#[^A-Za-z0-9]#i', '', $input);
$output = preg_replace('/[^A-Za-z0-9]/i', '', $input);
/[^A-Za-z0-9]/后面的字母 i 做什么?
另外^是什么意思?
What does the # sign do differently than the /?
$output = preg_replace('#[^A-Za-z0-9]#i', '', $input);
$output = preg_replace('/[^A-Za-z0-9]/i', '', $input);
And what does the letter i do after /[^A-Za-z0-9]/?
Also what does the ^ mean?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在某些语言中,什么类型的字符开始或结束正则表达式的模式部分并不重要,只要它在开头和结尾相同即可(我相信这是 Perl 的延续,可以说是第一个伟大的语言)正则表达式语言)。由于PHP遵循这个思路,所以
#
和/
是等价的。i
=“使此搜索不区分大小写”[^...]
=排除方括号之间的所有内容(^在此上下文中基本上表示“排除”)。您可以在此处了解有关正则表达式的更多信息。
In some languages, it does not matter what type of character starts or ends the pattern portion of the regular expression, so long as it is the same at the beginning and the end (I believe this is a holdover from Perl, arguably the first great regex language). Since PHP follows this line of thought,
#
and/
are equivalent.i
= "Make this search case insensitive"[^...]
= exclude everything between the square brackets (^ basically means "exclusion" in this context).You can learn a lot about regular expressions here.
这只是一个不同的分隔符。如果您要在正则表达式中大量使用斜杠,您不想每次都转义它,因此您指定一个散列(或其他字符,有很多可供选择)作为分隔符,以便它不需要逃避。
正则表达式末尾的
i
是一个修饰符,告诉 PHP 在执行匹配时忽略大小写。即字符A
和a
是等效的。使用i
修饰符时,无需使用A-Za-z
,因为az
已作为无大小写AZ 的一部分包含在内匹配。
克拉(即
^
)用作字符列表中的第一个字符时,意味着匹配该列表中不的任何内容。因此 [^abc] 匹配除字符a
、b
和c
之外的任何内容。It's just a different delimiter. If you're going to be using slashes in your regex a lot, you don't want to have to escape it every time, so you assign a hash (or another character, there are plenty to choose from) as the delimiter so that it doesn't need to be escaped.
The
i
at the end of the regex is a modifier telling PHP to disregard case when performing the match. i.e. the charactersA
anda
are equivalent. When using thei
modifier, there's no need to useA-Za-z
sincea-z
is included as part of the caselessA-Z
match.The carat (i.e.
^
), when used as the first character in a character list, means to match anything that is not in that list). So [^abc] matches anything but the charactersa
,b
, andc
.^
匹配字符串中的起始位置。在基于行的工具中,它匹配任何行的起始位置。您可以在 javascript 中使用此工具来查看差异:
这些在正则表达式中非常重要
'*'、'+' 和 '?',表示字符或序列出现的次数
可能会出现字符。
'*' 表示“零个或多个”
'+' 表示“一个或多个”
'?'意思是“零或一”
我也喜欢这个教程
^
Matches the starting position within the string. In line-based tools, it matches the starting position of any line.you can use this tool in javascript to see differences:
these are very important in regex
'*', '+', and '?', which denote the number of times a character or a sequence of
characters may occur.
'*' means "zero or more"
'+' means "one or more"
'?' means "zero or one"
Also I like this tutorial