文章有两个正则匹配图片的例子,头一个是获取文章中所有图片地址出来,第二个例子就是只要以http,https打开的图片地址,第二个例子多半用来采集远程图片,第一个例子多半用来获取字符串中图片地址或提取第一张图片.
例子1 获取字符串中所有图片:
- <?php
- $str='<p><img border="0" src="upfiles/2009/07/1246430143_1.jpg" alt=""/></p>';
- $pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
- preg_match_all($pattern,$str,$match);
- print_r($match);
- ?>
结果显示:
- Array
- (
- [0] => Array
- (
- [0] => <img border=”0″ src=”upfiles/2009/07/1246430143_1.jpg” alt=””/>
- )
-
- [1] => Array
- (
- [0] => upfiles/2009/0(www.phpfensi.com)7/1246430143_1.jpg
- )
-
- )
例子2,这个函数是提取站外以http,https
-
-
-
-
-
- function getimgs($str) {
- $reg = '/((http|https):\/\/)+(\w+\.)+(\w+)[\w\/\.\-]*(jpg|gif|png)/';
- $matches = array();
- preg_match_all($reg, $str, $matches);
- foreach ($matches[0] as $value) {
- $data[] = get_file($value);
- }
- return $data;
- }
|