PHP如何去除IMG标签?
在PHP中可以使用“preg_replace()”函数去除IMG标签,该函数作用是执行一个正则表达式的搜索和替换,使用时只需向第1个参数传入IMG标签正则,第2个为空,第3个为要操作的字符串即可。
IMG标签正则:/]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i
使用示例
<?php /*PHP正则提取图片img标记中的任意属性*/ $str = '<center><img src="/static/imghwm/default1.png" data-src="/uploads/images/20100516000.jpg" class="lazy" 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 src="/static/imghwm/default1.png" data-src="/uploads/images/20100516000.jpg" class="lazy" .+( style="max-width:90%"?\d*\"?).+ alt="PHP如何去除IMG標籤?" >/i',$str,$match); echo $match[1]; //3、取height preg_match('/<img src="/static/imghwm/default1.png" data-src="/uploads/images/20100516000.jpg" class="lazy" .+(height=\"?\d*\"?).+ alt="PHP如何去除IMG標籤?" >/i',$str,$match); echo $match[1]; //4、取src preg_match('/<img src="/static/imghwm/default1.png" data-src="/uploads/images/20100516000.jpg" class="lazy" .+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+ alt="PHP如何去除IMG標籤?" >/i',$str,$match); echo $match[1]; /*PHP正则替换图片img标记中的任意属性*/ //1、将替换为) print preg_replace('/(<img src="/static/imghwm/default1.png" data-src="/uploads/images/20100516000.jpg" class="lazy" .+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); ?>
推荐教程:《PHP教程》
以上是PHP如何去除IMG標籤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!