首頁 >後端開發 >PHP問題 >PHP如何去除IMG標籤?

PHP如何去除IMG標籤?

Guanhui
Guanhui原創
2020-06-15 16:10:433959瀏覽

PHP如何去除IMG標籤?

PHP如何去除IMG标签?

在PHP中可以使用“preg_replace()”函数去除IMG标签,该函数作用是执行一个正则表达式的搜索和替换,使用时只需向第1个参数传入IMG标签正则,第2个为空,第3个为要操作的字符串即可。

IMG标签正则:/]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i

使用示例

<?php
/*PHP正则提取图片img标记中的任意属性*/
$str = &#39;<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>&#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  src="/static/imghwm/default1.png"  data-src="/uploads/images/20100516000.jpg"  class="lazy" .+(   style="max-width:90%"?\d*\"?).+ alt="PHP如何去除IMG標籤?" >/i&#39;,$str,$match);
echo $match[1];
//3、取height
preg_match(&#39;/<img  src="/static/imghwm/default1.png"  data-src="/uploads/images/20100516000.jpg"  class="lazy" .+(height=\"?\d*\"?).+ alt="PHP如何去除IMG標籤?" >/i&#39;,$str,$match);
echo $match[1];
//4、取src
preg_match(&#39;/<img  src="/static/imghwm/default1.png"  data-src="/uploads/images/20100516000.jpg"  class="lazy" .+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+ alt="PHP如何去除IMG標籤?" >/i&#39;,$str,$match);
echo $match[1];
/*PHP正则替换图片img标记中的任意属性*/
//1、将替换为)
print preg_replace(&#39;/(<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&#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)\"?).+ alt="PHP如何去除IMG標籤?" >/i&#39;,"\${1} \${2}uc/images/\${3}>",$str);
?>


推荐教程:《PHP教程

以上是PHP如何去除IMG標籤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:php是什麼?下一篇:php是什麼?