Home > Article > Backend Development > Can php replace the text content of html?
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.
#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=[\'|\"](.*?)[\'|\"].*?[\/]?>/"; 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=[\'|\"](.*?)[\'|\"].*?[\/]?>/", function($m) use($host){ if(strpos($m[1],'http://') || strpos($m[1],'https://')){ return $m[0]; }else{ $img=preg_replace('#src="/#is', 'src="'.$host.'/',$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!