PHP extracts a simple instance of any attribute in the image img tag

  • 2020-12-05 17:07:45
  • OfStack


<?php
/* PHP Regular extract image img Any property in the tag  */
$str = '<center><img src="/uploads/images/20100516000.jpg" height="120" width="120"><br />PHP Regex extracts or changes images img Any property in the tag </center>';
//1 , take the whole picture code 
preg_match('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i',$str,$match);
echo $match[0];
//2 , take width attribute 
preg_match('/<img.+(width=\"?\d*\"?).+>/i',$str,$match);
echo $match[1];
//3 , take height attribute 
preg_match('/<img.+(height=\"?\d*\"?).+>/i',$str,$match);
echo $match[1];
//4 , take src
preg_match('/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i',$str,$match);
echo $match[1];
//1 Will, src="/uploads/images/20100516000.jpg" Replace with 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 Will, src="/uploads/images/20100516000.jpg" Replace with src="/uploads/uc/images/20100516000.jpg", And omit width and height 
print preg_replace('/(<img).+(src=\"?.+)images\/(.+\.(jpg|gif|bmp|bnp|png)\"?).+>/i',"\${1} \${2}uc/images/\${3}>",$str);
?>


Related articles: