How to get the first image of an article in a website as a thumbnail using PHP

墨辰丷
Release: 2023-03-29 13:04:01
Original
1549 people have browsed it

It is a very popular practice to retrieve the first picture in an article as a thumbnail for a list page. This is also the case for general themes in WordPress by default. Then let’s take a look at PHP to get the first picture of each article in the website. Image code example

<?php 
$temp=mt_rand(1,4); 
$pattern="/<[img|IMG].*?src=[\&#39;|\"](.*?(?:[\.gif|\.jpg|\.png]))[\&#39;|\"].*?[\/]?>/"; 
$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 
} 
 
?>
Copy after login

The above code calls the first image of the article by default. When the article has no image, it randomly calls 1.jpg, 2.jpg, 3.jpg, and 3.jpg under the theme style/images/random/. 4.jpg pictures. If you don’t want to call a random picture, you can modify it:

<?php 
$pattern="/<[img|IMG].*?src=[\&#39;|\"](.*?(?:[\.gif|\.jpg|\.png]))[\&#39;|\"].*?[\/]?>/"; 
$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图片 
} 
 
?>
Copy after login

Call the first picture of the article. If the article has no picture, call the default picture no-image.jpg

Summary: The above is the summary of this article All content, I hope it will be helpful to everyone's study.

Related recommendations:

Method to implement SMS verification code interface based on PHP

Sharing of simple methods to implement static page in PHP

PHP7’s image upload function based on curl

The above is the detailed content of How to get the first image of an article in a website as a thumbnail using PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!