Jquery中文网 www.jquerycn.cn
Jquery中文网 >  脚本编程  >  php  >  正文 php preg_match_all匹配文章中图片

php preg_match_all匹配文章中图片

发布时间:2017-11-20   编辑:www.jquerycn.cn
本文介绍下,php编程中使用 preg_match_all匹配文章中图片的方法,有需要的朋友参考下。

使用php获取网页中的图片并保存下来,使用preg_match_all用来匹配图片地址。

先来了解下 preg_match_all 函数:
int preg_match_all ( string pattern, string subject, array matches [, int flags] )执行一个全局正则表达式匹配
在 subject 中搜索所有与 pattern 给出的正则表达式匹配的内容并将结果以 flags 指定的顺序放到 matches 中。    
搜索到第一个匹配项之后,接下来的搜索从上一个匹配项末尾开始。  

flags 可以是下列标记的组合(注意把 PREG_PATTERN_ORDER 和 PREG_SET_ORDER 合起来用没有意义): 
PREG_PATTERN_ORDER  对结果排序使 $matches[0] 为全部模式匹配的数组,$matches[1] 为第一个括号中的子模式所匹配的字符串组成的数组,以此类推!

例子:
 

复制代码 代码示例:
<?php
$con = file_get_contents("http://www.jbxue.com/news/jb-1.html");
$pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/";
preg_match_all($pattern,$con,$match);
print_r($match);
?>

输出结果:
Array
(
    [0] => Array
        (
            [0] => <img src="http://www.jbxue.com/usr/themes/dddefault/images/logo.png" alt="脚本学堂" />
            [1] => <img style="display: block; margin-left: auto; margin-right: auto;" title="脚本学堂上线了" src="http://www.jbxue.com/usr/uploads/2012/09/531656480.jpg" alt="脚本学堂上线了2" />
            [2] => <img style="display: block; margin-left: auto; margin-right: auto;" src="http://www.jbxue.com/usr/uploads/2012/09/2647136297.jpg" alt="875EA1C00E50B4542797E24FA6E7E1F2.jpg" />
        )
    [1] => Array
        (
            [0] => http://www.jbxue.com/usr/themes/dddefault/images/logo.png
            [1] => http://www.jbxue.com/usr/uploads/2012/09/531656480.jpg
            [2] => http://www.jbxue.com/usr/uploads/2012/09/2647136297.jpg
        )
)

您可能感兴趣的文章:
php匹配图片地址的代码一例
php preg_match_all匹配文章中图片
php用preg_match_all匹配文章中的图片
使用 preg_replace 函数 匹配图片并加上链接的方法
PHP正则匹配日期和时间(时间戳转换)的例子
PHP正则匹配获取URL中域名的代码
php下载css中图片的实例代码
php匹配任何网址的正则表达式
php正则匹配重写html图片img路径的代码一例
PHP提取字符串中的图片地址2种方法

关键词: preg_match_all   
[关闭]