文章有兩個正則匹配圖片的例子,頭一個是獲取文章中所有圖片地址出來,第二個例子就是只要以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.companysz.com)7/1246430143_1.jpg
- )
- )
例子2,這個函數是提取站外以http,https
- /**
- * 提取字符串中圖片url地址
- * @param type $str
- * @return type
- */
- 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;
- }
|
新聞熱點
疑難解答