preg_match_all结合str_replace替换img php preg_match_all结合str_replace替换内容中所有img

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

preg_match_all结合str_replace替换img php preg_match_all结合str_replace替换内容中所有img

  2021-03-17 我要评论
想了解php preg_match_all结合str_replace替换内容中所有img的相关内容吗,在本文为您仔细讲解preg_match_all结合str_replace替换img的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:php,preg_match_all,str_replace,img,下面大家一起来学习吧。
采集回来的图片img标签中,有好多javascript脚本和无用的信息,必需过替换自己想要的,比如alt。先看看要过滤的内容,我随便复制出来:
复制代码 代码如下:

sdfsdfsdf<img alt=”3568df.com靓图” src=”http://www.aaa.com/upimg /080330/120D1232295023X0.gif” src=”http://www.eee.com/upimg/080330 /120D1232295023X0.gif” width=1 onclick=”javascript:; ” onload=”javascript:if(this.width>500){this.resized=true; this.style.width=500;}”>sfsdfsdfasdfsadf<img alt=”3568df.com靓图 ” src=”http://www.3568.com/upimg/080330 /120D1232295023X0.gif” src=”http://www.ddd.com/upimg/080330 /120D1232295023X0.gif” width=1 onclick=”javascript:; ” onload=”javascript:if(this.width>500){this.resized=true; this.style.width=500;}”>sdfsadf<img alt=”3568df.com靓图 ” src=”http://www.xxx.com/upimg/080330/120D1232295023X0.gif” src=”http://www.sss.com/upimg/080330/120D1232295023X0.gif” width=1 onclick=”javascript:;” onload=”javascript:if(this.width>500){this.resized=true;this.style.width=500;}”>sdfsdf

要把上面替换成形如:
复制代码 代码如下:

<img alt=”我的信息” src=”http://www.xxx.com/upimg /080330/120D1232295023X0.gif” src=”http://www.xxx.com/upimg/080330 /120D1232295023X0.gif” /> 其中src=”http://www.xxx.com/upimg/080330 /120D1232295023X0.gif” src=”http://www.xxx.com/upimg/080330 /120D1232295023X0.gif”这个地址要保留,因为图片用的都是源地址

方法大致是:先读取内容里的所以IMG标签,然后把每个IMG标签的SRC抽取出来,并且组合成自己的内容,最后进行替换。
preg_match_all就是我想要的函数,它能够把正则表达式匹配到的内容建立一个三维数组,你可以对它们进行遍历查找替换,不太了解的请查查手册,这里不作具体介绍。函数代码:
复制代码 代码如下:

function replace($str)
{
preg_match_all(”/<img(.*)(src=\”[^\"]+\”)[^>]+>/isU”, $str, $arr);
for($i=0,$j=count($arr[0]);$i<$j;$i++){
$str = str_replace($arr[0][$i],”<img alt=\”我的信息” “.$arr[2][$i].” />”,$str);
}
return $str;
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们