有时候我们会有这样一个需求,在一串html页面中,提取出整个img标签,或者是提取出img标签里的src属性,也就是我们所需要的图片链接,话不多说直接贴代码,代码如下:
function extract_img($tag) {
preg_match_all('/(id|alt|title|src)=("[^"]*")/i', $tag, $matches);
$ret = array();
foreach($matches[1] as $i => $v) {
$ret[$v] = $matches[2][$i];
}
return $ret;
}
$img_tag = '<img id="logo" title="我要吃鱼啊" src="http://www.baidu.net/wp-content/uploads/2015/06/2015-06-02.jpg" alt="我爱吃鱼" />';
$atts = extract_img($img_tag);
print_r($atts);
以下是程序执行后的返回结果:
返回结果
Array
(
[id] => "logo"
[src] => "http://www.devdo.net/wp-content/uploads/2015/06/2015-06-02.jpg"
[alt] => "我爱吃鱼"
[title] => "我爱吃鱼啊"
)
以下是我自用的代码,目的是为了抓取某个图片站的图片,但是这个站长对图片采集这块做了一定的处理,但是这种处理方式怎么可能难到程序猿呢
//需要提取的网页代码
$str='
';
function getSimpleImg($str = '')
{
if (!empty($str)) {
$result = preg_replace("/.*<img[^>]*srcset[=\s\"\']+([^\"\']*)[\"\'].*/", "$1", $str);
} else {
$result = '';
}
}
getSimpleImg($str);
function extract_attrib($tag) {
preg_match_all('/(srcset)=("[^"]*")/i', $tag, $matches);
// print_r($matches[2]);
$ret = array();
$img='';
foreach($matches[2] as $i => $v) {
if ($i%2==0) {
//$img.="<img src='$v' />"."<br>";
$v= str_replace("-200x200","",$v);
$v=str_replace("-300x300","",$v);
echo '<img src='."$v" .'/>';
}
}
return $img;
}
$atts = extract_attrib($str);
print_r($atts);