Home >Backend Development >PHP Tutorial >php正则表达式匹配img中任意属性的方法

php正则表达式匹配img中任意属性的方法

WBOY
WBOYOriginal
2016-06-23 13:17:311458browse

`<?php /*PHP正则提取图片img标记中的任意属性*/ $str = '<center><img  src="/uploads/images/20100516000.jpg"    style="max-width:90%"  style="max-width:90%" alt="php正则表达式匹配img中任意属性的方法" ><br />PHP正则提取或更改图片img标记中的任意属性</center>'; //1、取整个图片代码 preg_match('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i',$str,$match); echo $match[0]; //2、取width preg_match('/<img .+(   style="max-width:90%"?\d*\"?).+ alt="php正则表达式匹配img中任意属性的方法" >/i',$str,$match); echo $match[1]; //3、取height preg_match('/<img .+(height=\"?\d*\"?).+ alt="php正则表达式匹配img中任意属性的方法" >/i',$str,$match); echo $match[1]; //4、取src preg_match('/<img .+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+ alt="php正则表达式匹配img中任意属性的方法" >/i',$str,$match); echo $match[1]; (PS:T不错的php Q扣峮:276167802,验证:csl) /*PHP正则替换图片img标记中的任意属性*/ //1、将src="/uploads/images/20100516000.jpg"替换为src="/uploads/uc/images/20100516000.jpg") print preg_replace('/(<img .+src=\"?.+)(images\/)(.+\.(jpg|gif|bmp|bnp|png)\"?.+ alt="php正则表达式匹配img中任意属性的方法" >)/i',"\${1}uc/images/\${3}",$str); echo "<hr/>"; //2、将src="/uploads/images/20100516000.jpg"替换为src="/uploads/uc/images/20100516000.jpg",并省去宽和高 print preg_replace('/(<img ).+(src=\"?.+)images\/(.+\.(jpg|gif|bmp|bnp|png)\"?).+ alt="php正则表达式匹配img中任意属性的方法" >/i',"\${1} \${2}uc/images/\${3}>",$str); ?> `

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