php提取字符串中的图片地址的正则表达式
php提取字符串中的图片地址的正则表达式
function get_contentgallery($content){
$pattern='/<img.*?src=[\"|\']?(.*?)[\"|\']?\s.*?>/i';
preg_match_all($pattern,$content,$match);
$gallery=$match[1];
if($gallery){
$resn="";
foreach($gallery as $k =>$val){
/*$pathinfo=pathinfo($val);
$dirname=$pathinfo['dirname'];
$filename=$pathinfo['basename'];
if(preg_match('/(http:\/\/)|(https:\/\/)/i', $val)) {
$imgurl=$val;
}else{
$imgurl="https://www.ysenmedveterinary.com/".$val;
}
//echo $dirname."<br>";
getImage($imgurl,'upi',$filename);*/
if (file_exists(ROOT_PATH.$val)) {
$imagesize=getimagesize(ROOT_PATH.$val);
$img_width=$imagesize[0];
$img_height=$imagesize[1];
/*if($img_width>=180 && $img_height>150){*/
if($k==0){
$resn.=$val;
}else{
$resn.="|".$val;
}
/*}*/
//echo $val."<br>";
}else {
if($k==0){
$resn.=$val;
}else{
$resn.="|".$val;
}
//$resn .="|".$val;
}
}
$res=explode("|",$resn);
}else{
$res="";
}
return $res;
//print_r($match);
function get_contentgallery($content){
$pattern='/<img.*?src=[\"|\']?(.*?)[\"|\']?\s.*?>/i';
preg_match_all($pattern,$content,$match);
$gallery=$match[1];
if($gallery){
$resn="";
foreach($gallery as $k =>$val){
/*$pathinfo=pathinfo($val);
$dirname=$pathinfo['dirname'];
$filename=$pathinfo['basename'];
if(preg_match('/(http:\/\/)|(https:\/\/)/i', $val)) {
$imgurl=$val;
}else{
$imgurl="https://www.ysenmedveterinary.com/".$val;
}
//echo $dirname."<br>";
getImage($imgurl,'upi',$filename);*/
if (file_exists(ROOT_PATH.$val)) {
$imagesize=getimagesize(ROOT_PATH.$val);
$img_width=$imagesize[0];
$img_height=$imagesize[1];
/*if($img_width>=180 && $img_height>150){*/
if($k==0){
$resn.=$val;
}else{
$resn.="|".$val;
}
/*}*/
//echo $val."<br>";
}else {
if($k==0){
$resn.=$val;
}else{
$resn.="|".$val;
}
//$resn .="|".$val;
}
}
$res=explode("|",$resn);
}else{
$res="";
}
return $res;
//print_r($match);
}
PHP通过正则表达式获取网页中的所有图片,用到的函数有:file_get_contents() 函数把整个文件读入一个字符串中,preg_match_all函数进行全局正则表达式匹配,array_unique函数去除数组中重复的值
<?php
$url="http://sports.qq.com/photo/?pgv_ref=aio";
//file_get_contents() 函数把整个文件读入一个字符串中
$string=file_get_contents($url);
//preg_match_all函数进行全局正则表达式匹配。
preg_match_all("/<img([^>]*)\s*src=('|\")([^'\"]+)('|\")/",
$string,$matches);//带引号
//preg_match_all("/<img([^>]*)\ssrc=([^\s>]+)/",$string,$matches);//不带引号
$new_arr=array_unique($matches[0]);//去除数组中重复的值
foreach($new_arr as $key){
echo $key."</br>";
}
?>
代码运行结果将显示所有抓取的图片。
<img.*?src="(.*?)">