首页> 基础笔记 >PHP基础学习 >PHP正则 PHP正则
PHP正则函数preg_match_all()基础学习
作者:小萝卜 2019-08-22 【 PHP 正则 】 浏览 1632
简介函数preg_match_all() --执行全局正则表达式匹配int preg_match_all(string $pattern ,string $subject ,array &$matches [, int $flags])搜索subject中所有匹配pattern给定正则表达式 的匹配结果并且将它们以flag指定顺序输出到matches中. 参数flags是指定matches的数组格式。
函数preg_match_all() --执行全局正则表达式匹配
int preg_match_all(string $pattern ,string $subject ,array &$matches [, int $flags])
搜索subject中所有匹配pattern给定正则表达式 的匹配结果并且将它们以flag指定顺序输出到matches中. 参数flags是指定matches的数组格式。
实例1:
<?php
//声明一个可以匹配URL的正则表达式
$pattern = '/(https?|ftps?):\/\/(www|bbs)\.([^\.\/]+)\.(com|net|org)(\/[\w-\.\/\?\%\&\=]*)?/i';
//声明一个包含多个URL链接地址的多行文字
$subject = "网址为http://bbs.luowebs.com/index.php的位置是萝卜网络博客,
网址为http://www.baidu.com/index.php的位置是百度,
网址为http://www.google.com/index.php的位置是谷歌。";
$i = 1; //定义一个计数器,用来统计搜索到的结果数
//搜索全部的结果
if(preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER)) {
foreach($matches as $urls) { //循环遍历二维数组$matches
echo "搜索到第".$i."个URL为:".$urls[0]."<br>";
echo "第".$i."个URL中的协议为:".$urls[1]."<br>";
echo "第".$i."个URL中的主机为:".$urls[2]."<br>";
echo "第".$i."个URL中的域名为:".$urls[3]."<br>";
echo "第".$i."个URL中的顶域为:".$urls[4]."<br>";
echo "第".$i."个URL中的文件为:".$urls[5]."<br>";
$i++; //计数器累加
}
} else {
echo "搜索失败!";
}
实例2:
<?php
header("Content-Type:text/html;charset=utf-8");
//正则的匹配查找
echo "<pre>";
//将字串中的两位数字匹配出来(此正则匹配函数只做一次匹配)
preg_match("/[0-9]{2}/","as56df78as69df",$a);
print_r($a);
//Array ( [0] => 56 )
echo "<hr/>";
//将字串中的两位数字匹配出来(此正则匹配函数会做 全局匹配)
preg_match_all("/[0-9]{2}/","as56df78as69df",$a);
print_r($a);
//Array([0]=>Array ([0]=>56 [1]=>78 [2]=>69))
echo "<hr/>";
//匹配红色和蓝色的单词
preg_match_all("/(red|blue)/","adsredfqwblueeqw",$a);
print_r($a);
很赞哦! (0)