PHP 的 preg_match() 和 preg_match_all() 函数
preg_match() 和 preg_match_all() 函数的作用以及如何使用它们?
What do the preg_match() and preg_match_all() functions do and how can I use them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
preg_match
在第一个匹配之后停止查找。另一方面,preg_match_all
继续查找,直到完成整个字符串的处理。一旦找到匹配项,它就会使用字符串的其余部分来尝试应用另一个匹配项。http://php.net/manual/en/function.preg-match -all.php
preg_match
stops looking after the first match.preg_match_all
, on the other hand, continues to look until it finishes processing the entire string. Once match is found, it uses the remainder of the string to try and apply another match.http://php.net/manual/en/function.preg-match-all.php
preg_match 和 preg_match_all 函数使用 Perl 兼容的正则表达式。
您可以观看本系列以完全了解 Perl 兼容的正则表达式:https://www. youtube.com/watch?v=GVZOJ1rEnUg&list=PLfdtiltiRHWGRPyPMGuLPWuiWgEI9Kp1w
preg_match($pattern, $subject, &$matches, $flags, $offset)
preg_match
函数用于搜索对于$subject
字符串中的特定$pattern
,当第一次找到该模式时,它会停止搜索它。它在$matches
中输出匹配项,其中$matches[0]
将包含与完整模式匹配的文本,$matches[1]
将具有与第一个捕获的带括号的子模式匹配的文本,依此类推。preg_match()
输出示例:
preg_match_all($pattern, $subject, &$matches, $flags)
preg_match_all
函数搜索字符串中的所有匹配项并输出它们位于根据$flags
排序的多维数组 ($matches
) 中。当没有传递$flags
值时,它会对结果进行排序,以便$matches[0]
是完整模式匹配的数组,$matches[1] 是与第一个带括号的子模式匹配的字符串数组,依此类推。
preg_match_all()
输出示例:
Both preg_match and preg_match_all functions in PHP use Perl compatible regular expressions.
You can watch this series to fully understand Perl compatible regular expressions: https://www.youtube.com/watch?v=GVZOJ1rEnUg&list=PLfdtiltiRHWGRPyPMGuLPWuiWgEI9Kp1w
preg_match($pattern, $subject, &$matches, $flags, $offset)
The
preg_match
function is used to search for a particular$pattern
in a$subject
string and when the pattern is found the first time, it stops searching for it. It outputs matches in the$matches
, where$matches[0]
will contain the text that matched the full pattern,$matches[1]
will have the text that matched the first captured parenthesized sub-pattern, and so on.Example of
preg_match()
Output:
preg_match_all($pattern, $subject, &$matches, $flags)
The
preg_match_all
function searches for all the matches in a string and outputs them in a multi-dimensional array ($matches
) ordered according to$flags
. When no$flags
value is passed, it orders results so that$matches[0]
is an array of full pattern matches,$matches[1]
is an array of strings matched by the first parenthesized sub-pattern, and so on.Example of
preg_match_all()
Output:
一个具体的例子:
A concrete example: