php正则提取html图片(img)src地址与任意属性的方法

简单版:

  1. <?php
  2. header("Content-Type: text/html;charset=utf-8");
  3. $str = '<div class="ui-block-a" align="center">
  4. <a href="online-39.html" rel="external nofollow" ><img class="lazy" width="131" height="177" src="http://files.jb51.net/file_images/game/201702/2017020716154162.jpg"/>
  5. <h3>2014年</h3></a>
  6. </div>';
  7. $imgpreg = "/<img (.*?) src=\"(.+?)\".*?>/";
  8. preg_match($imgpreg,$str,$img);
  9. $mycount=count($img)-1;
  10. $imgval = $iim[$mycount];
  11. if(!emptyempty($imgval)){
  12. echo $imgval;
  13. }else{
  14. echo 'no';
  15. }
  16. ?>

详细版:

  1. <?php
  2. /*PHP正则提取图片img标记中的任意属性*/
  3. $str = '<center><img src="/uploads/images/2017020716154162.jpg" height="120" width="120"><br />PHP正则提取或更改图片img标记中的任意属性</center>';
  4. //1、取整个图片代码
  5. preg_match('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i',$str,$match);
  6. echo $match[0];
  7. //2、取width
  8. preg_match('/<img.+(width=\"?\d*\"?).+>/i',$str,$match);
  9. echo $match[1];
  10. //3、取height
  11. preg_match('/<img.+(height=\"?\d*\"?).+>/i',$str,$match);
  12. echo $match[1];
  13. //4、取src
  14. preg_match('/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i',$str,$match);
  15. echo $match[1];
  16. /*PHP正则替换图片img标记中的任意属性*/
  17. //1、将src="/uploads/images/20100516000.jpg"替换为src="/uploads/uc/images/2017020716154162.jpg")
  18. print preg_replace('/(<img.+src=\"?.+)(images\/)(.+\.(jpg|gif|bmp|bnp|png)\"?.+>)/i',"\${1}uc/images/\${3}",$str);
  19. echo "<hr/>";
  20. //2、将src="/uploads/images/20100516000.jpg"替换为src="/uploads/uc/images/2017020716154162.jpg",并省去宽和高
  21. print preg_replace('/(<img).+(src=\"?.+)images\/(.+\.(jpg|gif|bmp|bnp|png)\"?).+>/i',"\${1} \${2}uc/images/\${3}>",$str);
  22. ?>