Home >Backend Development >PHP Tutorial >PHP function sample code to obtain the first image of each article in the website
Calling the first picture in the article as the list pageThumbnail image is a very popular practice, and the same is true by default for general themes in WordPress, so let’s do it together next Take a look at the code example of PHP getting the first picture of each article on the website
<?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 picture of the article by default. When the article has no picture, it randomly calls the theme style/ 1.jpg, 2.jpg, 3.jpg, 4.jpg pictures under 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 picture of the article. If the article has no picture, call the default picture no-image.jpg
The above is the detailed content of PHP function sample code to obtain the first image of each article in the website. For more information, please follow other related articles on the PHP Chinese website!