PHP regular expression matching to get the image address without suffix

$content ="<div style='margin: 5px 0px;height: 100px;'><a class='text' href='/article/10?src=u1' target='_blank' rel='noopener'><img src='/uploads/files_user1/answer/5f524457e501e894256.png' alt='eed'>33</a></div>";

function getImages($content,$order=0){
    //匹配有后缀图片
    /*    $pattern="/<img.*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.jpeg|\.?]))[\'|\"].*?[\/]?>/";*/
    //匹配无后缀图片
    $pattern="/<img.*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/";
    preg_match_all($pattern,$content,$match);
    if(!empty($match[1])){
        if($order == 0){
            return $match[1];
        }
        if(!empty($match[1][$order-1])){
            return $match[1][$order-1];
        }
    }
    return [];
}
var_dump(getImages($content,$order=0));
//array(1) { [0]=> string(51) "/uploads/files_user1/answer/5f524457e501e894256.png" } 

Leave a Reply

Your email address will not be published.

en_USEnglish