PHP Regularly obtains the value of each attribute of IMG

<?php
header('Content-Type: text/html; charset=utf-8');

/**
 * $str, the content to be processed
 * $ext, the extension to match
 */
function img_match($str,$ext){
    $list = array();
    //First remove all img tag text
    $c1 = preg_match_all('/<img\s.*?>/', $str, $m1);
    //Get attributes for all img tags
    for($i=0; $i<$c1; $i++){
        // match all attributes
        $c2 = preg_match_all('/(\w+)\s*=\s*(?:(?:(["\'])(.*?)(?=\2))|([^\/\s]*))/', $m1[0][$i], $m2);
        //Restructure the matched result
        for($j=0; $j<$c2; $j++) {
            $list[$i][$m2[1][$j]] = !empty($m2[4][$j]) ? $m2[4][$j] : $m2[3][$j];
        }
    }
    return $list;
}

//List image suffixes to achieve multi-extension matching
$ext = 'jpg|jpeg|gif|bmp|png';

// imitate a website
$str = <<<___
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Who asks you to read, the fragrance floats when the water falls</title>
</head>
<body>
<img src="http://dl2.iteye.com/upload/attachment/0126/9800/65dcffd0-304b-3d61-b48e-ca9f0393dfd3.jpg" alt="img1" title="img1" onClick="test();">
<p>onestopweb.iteye.com</p>
<img src="http://dl2.iteye.com/upload/attachment/0126/9802/9190af90-ba41-3901-b9e0-dda6d9e9b378.jpg" alt="img2" title="img2" onClick="test2();">
<img src="http://dl2.iteye.com/upload/attachment/0126/9804/25b3a4bc-0625-3483-8fcb-c21a8b813708.jpg" title="img3" onClick="test();">
<img src="http://dl2.iteye.com/upload/attachment/0126/9806/e54a93ad-f3bf-38ec-8194-952a387a6785.jpg" alt="img4" title="img4">
</body>
</html>
___;

//test effect
$img_list = img_match($str,$ext);
var_dump($img_list);

 

Effect picture:

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326945116&siteId=291194637