- 时间:2020-09-24 10:42 编辑: 来源: 阅读:
- 扫一扫,手机访问
摘要:解析PHP正则提取或替换img标记属性
<?php
[b]/*PHP正则提取图片img标记中的任意属性*/
[/b]$str = '<center><img src="/uploads/images/20100516000.jpg" height="120" width="120"><br />PHP正则提取或更改图片img标记中的任意属性</center>';
[b]//1、取整个图片代码
[/b]preg_match('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i',$str,$match);
echo $match[0];
[b]//2、取width
[/b]preg_match('/<img.+(width=\"?\d*\"?).+>/i',$str,$match);
echo $match[1];
[b]//3、取height
[/b]preg_match('/<img.+(height=\"?\d*\"?).+>/i',$str,$match);
echo $match[1];
[b]//4、取src
[/b]preg_match('/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i',$str,$match);
echo $match[1];
[b]/*PHP正则替换图片img标记中的任意属性*/
[/b]//1、将src="/uploads/images/20100516000.jpg"替换为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、将src="/uploads/images/20100516000.jpg"替换为src="/uploads/uc/images/20100516000.jpg",并省去宽和高
print preg_replace('/(<img).+(src=\"?.+)images\/(.+\.(jpg|gif|bmp|bnp|png)\"?).+>/i',"\${1} \${2}uc/images/\${3}>",$str);
?>