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

伊谢尔伦
Release: 2023-03-02 21:22:01
Original
2732 people have browsed it

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

要匹配的字符串:

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

正则表达式:

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

正则匹配输出结果:

x
image/ad1.gif
image/ad2.gif
Copy after login

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); 

?>
Copy after login

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

//正则表达式 <script language="javascript">
Copy after login
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;
Copy after login
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>
Copy after login


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!