preg_match() 和 preg_match_all() 函数是什么,我该如何使用它们?
preg_match() 和 preg_match_all() 函数是什么,我该如何使用它们?
preg_match
在找到第一个匹配项后就停止查找。而preg_match_all
则会继续查找,直到处理完整个字符串为止。一旦找到匹配项,它会使用剩余的字符串来尝试应用另一个匹配项。
PHP中的preg_match和preg_match_all函数都使用与Perl兼容的正则表达式。
您可以观看这个系列视频,全面了解Perl兼容的正则表达式:https://www.youtube.com/watch?v=GVZOJ1rEnUg&list=PLfdtiltiRHWGRPyPMGuLPWuiWgEI9Kp1w
preg_match
函数用于在$subject
字符串中搜索特定的$pattern
,当找到第一个匹配项时,停止搜索。它会输出匹配结果到$matches
中,其中$matches[0]
包含与完整模式匹配的文本,$matches[1]
包含与第一个捕获括号内的子模式匹配的文本,以此类推。
preg_match()
示例<?php
preg_match(
"|<[^>]+>(.*)</[^>]+>|U",
"<b>example: </b><div align=left>this is a test</div>",
$matches
);
var_dump($matches);
输出:
array(2) {
[0]=>
string(16) "<b>example: </b>"
[1]=>
string(9) "example: "
}
preg_match_all
函数在一个字符串中搜索所有匹配项,并将它们按照$flags
的顺序输出到一个多维数组($matches
)中。当没有传递$flags
值时,它会按照一定的顺序排列结果,使得$matches[0]
是一个包含完整模式匹配的数组,$matches[1]
是第一个括号子模式匹配的字符串数组,以此类推。
preg_match_all()
示例<?php
preg_match_all(
"|<[^>]+>(.*)</[^>]+>|U",
"<b>example: </b><div align=left>this is a test</div>",
$matches
);
var_dump($matches);
输出:
array(2) {
[0]=>
array(2) {
[0]=>
string(16) "<b>example: </b>"
[1]=>
string(36) "<div align=left>this is a test</div>"
}
[1]=>
array(2) {
[0]=>
string(9) "example: "
[1]=>
string(14) "this is a test"
}
}
preg_match("/find[ ]*(me)/", "find me find me", $matches):
$matches = Array(
[0] => find me
[1] => me
)
preg_match_all("/find[ ]*(me)/", "find me find me", $matches):
$matches = Array(
[0] => Array
(
[0] => find me
[1] => find me
)
[1] => Array
(
[0] => me
[1] => me
)
)
preg_grep("/find[ ]*(me)/", ["find me find me", "find me findme"]):
$matches = Array
(
[0] => find me find me
[1] => find me findme
)