本篇文章是對PHP正則提取或替換img標記屬性進行了詳細的分析介紹
簡單版:
<?php
header("Content-Type: text/html;charset=utf-8");
$str = '<div class="ui-block-a" align="center">
<a href="#"><img class="lazy" width="131" height="177" src="/uploads/image/20161220/2016122010425.jpg"/>
<h3>2016年</h3></a>
</div>';
$imgpreg = "/<img (.*?) src=\"(.+?)\".*?>/";
preg_match($imgpreg,$str,$img);
$mycount=count($img)-1;
$imgval = $iim[$mycount];
if(!empty($imgval)){
echo $imgval;
}else{
echo 'no';
}
?>
詳細版:
<?php
/*PHP正則提取圖片img標記中的任意屬性*/
$str = '<center><img src="/uploads/images/20100516000.jpg" height="120" width="120"><br />PHP正則提取或更改圖片img標記中的任意屬性</center>';
//1、取整個圖片代碼
preg_match('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i',$str,$match);
echo $match[0];
//2、取width
preg_match('/<img.+(width=\"?\d*\"?).+>/i',$str,$match);
echo $match[1];
//3、取height
preg_match('/<img.+(height=\"?\d*\"?).+>/i',$str,$match);
echo $match[1];
//4、取src
preg_match('/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i',$str,$match);
echo $match[1];
/*PHP正則替換圖片img標記中的任意屬性*/
//1、將src="/uploads/images/20100516000.jpg"替換為src="/uploads/uc/images/20100516000.jpg")
print preg_replace('/(<img.+src=\"?.+)(images\/)(.+\.(jpg|gif|bmp|bnp|png)\"?.+>)/i',"\${1}uc/images/\${3}",$str);
echo "<hr/>";
//2、將src="/uploads/images/20100516000.jpg"替換為src="/uploads/uc/images/20100516000.jpg",並省去寬和高
print preg_replace('/(<img).+(src=\"?.+)images\/(.+\.(jpg|gif|bmp|bnp|png)\"?).+>/i',"\${1} \${2}uc/images/\${3}>",$str);
?>
*