This article introduces to you about PHP according to different conditions to replace a piece of HTML code in the different IMG tags, there is a certain reference value, the need for friends can refer to, I hope to help you.
First, the demand
The requirement is to get a piece of HTML code that contains multiple IMG tags. The requirement is to obtain the SRC attribute of these IMG tags before doing business writing. After the business has been written, replace the new SRC content with the different IMG tags.
This part of the logic sounds very simple, but the actual operation is still a bit difficult, the following is the process of solving the problem.
Second, the realization process
1. Get the SRC attribute of all IMG tags in html code
Preg_match_all ('/]*?src= ' ([^ "]*?)" [^>]*?>/i ', $content, $match); $SRCARR = $match [1];
Here is the use of regular matching, which $content
is the HTML code we want to extract, $match
is the array to get to. You can print it out $srcArr
to get an array of all the SRC attributes. Here we can process our logic through a loop.
2. When the logic is processed, we need to assign the processed SRC to each img tag separately.
$rules = ' #]*?) ># '; Preg_replace ($rules, "
There's still a regular match, but if we match it this way, we'll replace the SRC attribute of all the IMG tags $base64
, which is obviously not the result we want.
3. Final plan
Declare regular matching rules $rules = ' #]*?) ># '; Here is the loop, which matches the corresponding IMG tag for ($i =0; $i < $count; $i + +) { //key is this preg_replace_callback function, which is replaced by the traditional regular One more callback function allows us to write our own logic, use () inside the parameters we need $newContent = preg_replace_callback (' #]*?) ># ', function ($m) use ($id, $i, $base) { //var_dump ($m [0]); The $m[0 here] represents the first image address to match //The $this->is_replace here is a function of my own, which belongs to the judging condition if ($this->is_replace ($m [$i], $id, $i) { //if compliant, replace with $base64[$i] return "
This function is really powerful, so that we can add their own logic in the regular match, great.