Home  >  Article  >  Backend Development  >  php preg_match_all combined with str_replace to replace all img_PHP tutorials in the content

php preg_match_all combined with str_replace to replace all img_PHP tutorials in the content

WBOY
WBOYOriginal
2016-07-21 15:48:59869browse

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. Let’s take a look at the content to be filtered first. I copied it casually:

Copy code The code is as follows:

sdfsdfsdf“3568df.com500){this.resized=true; this.style.width=500;}”>sfsdfsdfasdfsadf”3568df.com500){this.resized=true; this.style.width=500;}”>sdfsadf”3568df.com500){this.resized=true;this.style.width=500;}”>sdfsdf

Replace the above into the following shape:
Copy code The code is as follows:

”My where src=”http://www.xxx.com /upimg/080330 /120D1232295023X0.gif” src=”http://www.xxx.com/upimg/080330 /120D1232295023X0.gif” This address should be retained because the pictures use the source address

The method is roughly: first read all the IMG tags in the content, then extract the SRC of each IMG tag, combine it into its own content, and finally replace it.
preg_match_all is the function I want. It can create a three-dimensional array of content matched by regular expressions. You can traverse, search 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:
Copy code The code is as follows:

function replace($str)
{
preg_match_all( ”/]+>/isU”, $str, $arr);
for($i=0,$ j=count($arr[0]);$i<$j;$i++){
$str = str_replace($arr[0][$i],””My",$str);
}
return $str;
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/319663.htmlTechArticleThere are a lot of javascript scripts and useless information in the collected image img tags. You must replace the ones you want. , such as alt. Let’s take a look at the content to be filtered first. I just copied it out:...
Statement:
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