Home > Article > Backend Development > How to implement html content replacement in php
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.
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=[\'|\"](.*?)[\'|\"].*?[\/]?>/"; 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=[\'|\"](.*?)[\'|\"].*?[\/]?>/", 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, 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!