Home > Article > Backend Development > PHP code example to get the first image of each article in the website, _PHP tutorial
<?php $temp=mt_rand(1,4); $pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/"; $content = $article->Content; //文章内容 preg_match_all($pattern,$content,$matchContent); if(isset($matchContent[1][0])){ $temp=$matchContent[1][0]; }else{ $temp="images/random/$temp.jpg";//需要在相应位置放置4张jpg的文件,名称为1,2,3,4 } ?>
The above code calls the first image of the article by default. When the article has no image, it randomly calls the 1.jpg, 2.jpg, 3.jpg, and 4.jpg images under the theme style/images/random/. If you don’t want to call a random picture, you can modify it:
<?php $pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/"; $content = $article->Content; //文章内容 preg_match_all($pattern,$content,$matchContent); if(isset($matchContent[1][0])){ $temp=$matchContent[1][0]; }else{ $temp="./images/no-image.jpg";//在相应位置放置一张命名为no-image的jpg图片 } ?>
Call the first image of the article. If the article has no image, call the default image no-image.jpg