Home > Backend Development > PHP Tutorial > php preg_match_all combined with str_replace replaces all img in the content

php preg_match_all combined with str_replace replaces all img in the content

高洛峰
Release: 2023-03-04 17:08:01
Original
2175 people have browsed it

There are a lot of javascript scripts and useless information in the collected image img tags. You must replace what you want, such as alt. First look at the content to be filtered, I copied it casually:

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
Copy after login

To replace the above into the form:

<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”这个地址要保留,因为图片用的都是源地址
Copy after login

The method is roughly: first read all the IMG tags in the content, and then The SRC of each IMG tag is extracted, combined into its own content, and finally replaced.
preg_match_all is the function I want. It can create a three-dimensional array of the content matched by the regular expression. You can traverse them to find and replace them. If you don’t know much about it, please check the manual. I won’t introduce it in detail here. Function code:

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; 
}
Copy after login

For more php preg_match_all combined with str_replace to replace all img related articles in the content, please pay attention to the PHP Chinese website!


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template