目录

PHP preg_match_all() 函数

❮ PHP 正则表达式参考

示例

查找字符串中所有出现的 "ain":

<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
if(preg_match_all($pattern, $str, $matches)) {
  print_r($matches);
}
?>
亲自试一试 »

定义和用法

这个preg_match_all()函数返回在字符串中找到的模式的匹配数,并用找到的匹配填充变量。


语法

preg_match_all( pattern, input, matches, flags, offset)

参数值

Parameter Description
pattern Required. Contains a regular expression indicating what to search for
input Required. The string in which the search will be performed
matches Optional. The variable used in this parameter will be populated with an array containing all of the matches that were found
flags Optional. A set of options that change how the matches array is structured.

One of the following structures may be selected:
  • PREG_PATTERN_ORDER - Default. Each element in the matches array is an array of matches from the same grouping in the regular expression, with index 0 corresponding to matches of the whole expression and the remaining indices for subpattern matches.
  • PREG_SET_ORDER - Each element in the matches array contains matches of all groupings for one of the found matches in the string.
Any number of the following options may be applied:
  • PREG_OFFSET_CAPTURE - When this option is enabled, each match, instead of being a string, will be an array where the first element is a substring containing the match and the second element is the position of the first character of the substring in the input.
  • PREG_UNMATCHED_AS_NULL - When this option is enabled, unmatched subpatterns will be returned as NULL instead of as an empty string.
offset Optional. Defaults to 0. Indicates how far into the string to begin searching. The preg_match() function will not find matches that occur before the position given in this parameter

技术细节

返回值: 返回找到的匹配数,如果发生错误则返回 false
PHP 版本: 4+
变更日志: PHP 7.2 - 添加了 PREG_UNMATCHED_AS_NULL 标志

PHP 5.4 - matches 参数变为可选

PHP 5.3.6 - 当偏移量长于输入长度时,该函数返回 false

PHP 5.2.2 - 除了之前的 (?P<name>) 语法之外,命名子模式还可以使用 (?'name') 和 (? <name>) 语法

更多示例

示例

使用 PREG_PATTERN_ORDER 设置结构火柴数组。在此示例中,中的每个元素火柴数组包含正则表达式分组之一的所有匹配项。

<?php
$str = "abc ABC";
$pattern = "/((a)b)(c)/i";
if(preg_match_all($pattern, $str, $matches, PREG_PATTERN_ORDER)) {
  print_r($matches);
}
?>
亲自试一试 »

❮ PHP 正则表达式参考