Home  >  Article  >  Backend Development  >  How to implement html content replacement in php

How to implement html content replacement in php

藏色散人
藏色散人Original
2020-11-24 09:29:503920browse

php How to replace html content: First create an HTML sample file; then modify the content in html through the "preg_match_all($pattern,htmlspecialchars_decode($a),$match);" method.

How to implement html content replacement in php

Recommended: "PHP Video Tutorial"

The operating environment of this tutorial: windows7 system, PHP5. Version 6, this method is suitable for all brands of computers.

php modifies the content in html

It is known that the following piece of html

$a="<p><img src=\"/upload/store/1/ue/image/1568282125833264.png\" title=\"1568282125833264.png\" alt=\"1.png\"/><img src=\"http://dimg04.c-ctrip.com/images/300q12000000rq2t956CB.jpg\" alt=\"undefined\"/><img src=\"https://dimg04.c-ctrip.com/images/300m12000000sdsca92E2.jpg\"/><img src=\"https://dimg04.c-ctrip.com/images/300w12000000rutmrD6CB.jpg\" alt=\"undefined\"/><img src=\"https://dimg04.c-ctrip.com/images/300u12000000rorex415F.jpg\" alt=\"undefined\"/><img src=\"http://dimg04.c-ctrip.com/images/300k12000000rsyxgBA05.jpg\" alt=\"undefined\"/></p>"

contains http, https and the url of the local relative path

Common usage:

$pattern="/<img.*?src=[\&#39;|\"](.*?)[\&#39;|\"].*?[\/]?>/";
preg_match_all($pattern,htmlspecialchars_decode($a),$match);
if(!empty($match[1])){
    print_r($match[1]);
}else{
echo "没得";
}

First match all in the loop $match[1]

After the loop foreach($match[1 ] as $val){preg_replace('#src="'.$val.'"/#is', 'src="aaaaa/',$a);}

I think this is quite troublesome

Upgrade usage:

$host="http://mp.csdn.net"
$newContent =  preg_replace_callback("/<img.*?src=[\&#39;|\"](.*?)[\&#39;|\"].*?[\/]?>/", function($m) use($host){

   if(strpos($m[1],&#39;http://&#39;) || strpos($m[1],&#39;https://&#39;)){
       return $m[0];
   }else{
       $img=preg_replace(&#39;#src="/#is&#39;, &#39;src="&#39;.$host.&#39;/&#39;,$m[0]);
       return $img;
   }
}, $a);

Although this method is rarely used, the effect is super good when batch processing!

I personally like this kind of closure function. The code is very readable

The above is the detailed content of How to implement html content replacement in php. For more information, please follow other related articles on the PHP Chinese website!

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