函数名称:preg_match_all() 适用版本:PHP 4、PHP 5、PHP 7 函数描述:preg_match_all() 函数在字符串中搜索匹配正则表达式的所有结果,并将结果保存在一个数组...
函数名称:preg_match_all()
适用版本:PHP 4、PHP 5、PHP 7
函数描述:preg_match_all() 函数在字符串中搜索匹配正则表达式的所有结果,并将结果保存在一个数组中。
用法: preg_match_all(string $pattern, string $subject, array &$matches, int $flags = PREG_PATTERN_ORDER, int $offset = 0): int|false
参数:
返回值:
示例:
$pattern = '/[0-9]+/';
$subject = 'There are 123 apples and 456 oranges.';
$matches = array();
if (preg_match_all($pattern, $subject, $matches)) {
echo "匹配到的次数:" . count($matches[0]) . "<br>";
echo "匹配到的结果:" . implode(", ", $matches[0]);
} else {
echo "没有匹配到结果。";
}
输出:
匹配到的次数:2
匹配到的结果:123, 456
在以上示例中,我们使用正则表达式 /[0-9]+/ 来匹配字符串中的所有数字。函数执行后,将匹配到的次数和结果输出到浏览器。