PHP preg_match_all() 函数
示例
在字符串中查找所有“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);
}
?>
自己动手试一试 »
定义和用法
The preg_match_all()
function returns the number of matches of a pattern that were found in a string and populates a variable with the matches that were found。
语法
preg_match_all(pattern, input, matches, flags, offset)
参数值
参数 | 描述 |
---|---|
pattern | 必需。包含一个正则表达式,指示要搜索的内容 |
input | 必需。要在其中执行搜索的字符串 |
matches | 可选。此参数中的变量将用一个包含所有找到的匹配项的数组进行填充 |
flags | 可选。一组选项,用于更改匹配项数组的结构。 可以选择以下结构之一
|
offset | 可选。默认为 0。指示从字符串的哪个位置开始搜索。preg_match() 函数将不会找到在该参数给定的位置之前的匹配项 |
技术详情
返回值 | 返回找到的匹配项的数量,如果发生错误则返回 false |
---|---|
PHP 版本 | 4+ |
更新日志 | PHP 7.2 - 添加了 PREG_UNMATCHED_AS_NULL 标志 PHP 5.4 - matches 参数变得可选 PHP 5.3.6 - 当 offset 长于 input 的长度时,函数返回 false PHP 5.2.2 - 除了之前的 (?P<name>) 语法外,命名子模式还可以使用 (?'name') 和 (? <name>) 语法 |
更多示例
示例
使用 PREG_PATTERN_ORDER 设置 matches 数组的结构。在此示例中,matches 数组中的每个元素都包含正则表达式一个分组的所有匹配项。
<?php
$str = "abc ABC";
$pattern = "/((a)b)(c)/i";
if(preg_match_all($pattern, $str, $matches, PREG_PATTERN_ORDER)) {
print_r($matches);
}
?>
自己动手试一试 »
❮ PHP 正则表达式参考