Parse PHP regulars to extract or replace img tag attributes

  • 2020-06-22 23:59:30
  • OfStack

The core code


<?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
preg_match('/<img.+(width=\"?\d*\"?).+>/i',$str,$match);
echo $match[1];

//3 , take height
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];

/*PHP Regular replacement image img Any property in the tag */
//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);
?>

PHP gets all image address regular expressions

All images without pictures address matching:

preg_match_all('/(\s+src\s?\=)\s?[\'|"]([^\'|"]*)/is', $request- > input('detail_content'), $match);

Take data: image / :

preg_match_all('/(\s+src\s?\=)\s?[\'|"]([^\'|"]*)[data]/is', $request- > input('detail_content'), $match);

PHP gets all image addresses in a 1-segment string

Sometimes we need to get the article content or string of all the image address, so the first thing we think of is regular matching, how to achieve, the following is the site's pro test method


$str = '<p><img src="/upload/20180621/1529561322214.png" /></p><p><img src="/Home/images/404.jpg" style="" title="404.jpg"/></p><p><img src="/upload/20180621/1529561322214.png" style="" title="1529561322214.png"/></p><p><br/></p>';
$preg = '/<img.*?src=[\"|\']?(.*?)[\"|\']?\s.*?>/i';// matching img A regular expression for a tag 
preg_match_all($preg, $str, $allImg);// I'm going to match everything here img
echo '<pre>';
print_r($allImg);

The output is as follows


(  
[0] => Array  
(  
  [0] => <img src="/upload/20180621/1529561322214.png" />  
  [1] => <img src="/Home/images/404.jpg" style="" title="404.jpg"/>  
  [2] => <img src="/upload/20180621/1529561322214.png" style="" title="1529561322214.png"/>  
)  
[1] => Array  
(  
  [0] => /upload/20180621/1529561322214.png  
  [1] => /Home/images/404.jpg  
  [2] => /upload/20180621/1529561322214.png  
)  
)

Related articles: