Home  >  Article  >  Backend Development  >  Can php replace the text content of html?

Can php replace the text content of html?

藏色散人
藏色散人Original
2021-09-19 09:39:031907browse

php can replace the text content of html. The replacement method is: 1. Replace through the "preg_match_all($pattern,htmlspecialchars_decode($a)...);" method; 2. Replace through the preg_replace_callback method.

Can php replace the text content of html?

#The operating environment of this article: Windows7 system, PHP7.1, Dell G3 computer.

Can php replace the text content of html?

php replaces 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>"

There are URLs containing http, https and local relative paths

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 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, it is batch processing The effect is super good!

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

Recommended learning: "PHP Video Tutorial

The above is the detailed content of Can php replace the text content of html?. 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