【发布时间】:2022-02-23 10:35:46
【问题描述】:
preg_match() 和 preg_match_all() 函数有什么作用以及如何使用它们?
【问题讨论】:
-
@Philip:是的,我明白了,但我不明白。
-
文档没有解释这 2 之间的区别。花了一点时间阅读,但这里的人给出的答案节省了很多时间。
标签: php preg-match preg-match-all
preg_match() 和 preg_match_all() 函数有什么作用以及如何使用它们?
【问题讨论】:
标签: php 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
)
【讨论】: