Home  >  Article  >  Backend Development  >  Regular expression to extract the value of the src attribute of the img element

Regular expression to extract the value of the src attribute of the img element

伊谢尔伦
伊谢尔伦Original
2016-12-02 11:34:552681browse

本文为大家介绍如果从 img 中获取图片的链接地址 src 属性值。

要匹配的字符串:

<img src=image/ad1.gif width="128" height="36"/><img src=&#39;image/ad2.gif&#39; width="128" height="36" />

正则表达式:

<img[\s]+src[\s]*=[\s]*(([&#39;"](?<src>[^&#39;"]*)[\&#39;"])|(?<src>[^\s]*))

正则匹配输出结果:

x
image/ad1.gif
image/ad2.gif

PHP正则提取或 img 元素的 src 属性值:

<?

php /*PHP正则提取图片img标记中的任意属性*/
$str = &#39;<center><img src="/uploads/images/20100516000.jpg" height="120" width="120"><br />PHP正则提取或更改图片img标记中的任意属性</center>&#39;; 
//1、取整个图片代码 preg_match(&#39;/<\s*img\s+[^>]*?src\s*=\s*(\&#39;|\")(.*?)\\1[^>]*?\/?\s*>/i&#39;,$str,$match); echo $match[0]; 
//2、取width preg_match(&#39;/<img.+(width=\"?\d*\"?).+>/i&#39;,$str,$match); echo $match[1]; 
//3、取height preg_match(&#39;/<img.+(height=\"?\d*\"?).+>/i&#39;,$str,$match); echo $match[1]; 
//4、取src preg_match(&#39;/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i&#39;,$str,$match); echo $match[1]; /*PHP正则替换图片img标记中的任意属性*/

//1、将src="/uploads/images/20100516000.jpg"替换为src="/uploads/uc/images/20100516000.jpg") 
print preg_replace(&#39;/(<img.+src=\"?.+)(images\/)(.+\.(jpg|gif|bmp|bnp|png)\"?.+>)/i&#39;,"\${1}uc/images/\${3}",$str); echo "<hr/>";

//2、将src="/uploads/images/20100516000.jpg"替换为src="/uploads/uc/images/20100516000.jpg",并省去宽和高 
print preg_replace(&#39;/(<img).+(src=\"?.+)images\/(.+\.(jpg|gif|bmp|bnp|png)\"?).+>/i&#39;,"\${1} \${2}uc/images/\${3}>",$str); 

?>

Js正则表达式提取图片地址

//正则表达式 <script language="javascript">
var a=&#39;<P><IMG src="http://bbs.cn.yimg.com/user_img/200701/31/jisuanji986_117025184198149.jpg" mce_src="http://bbs.cn.yimg.com/user_img/200701/31/jisuanji986_117025184198149.jpg"></P>&#39;
var b=/<IMG src=\"([^\"]*?)\">/gi var s=a.match(b) for(var i= 0;i<s.length;i++) { alert(s[i]); alert(RegExp.$1) } </script>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn