Heim  >  Artikel  >  Backend-Entwicklung  >  PHP获取网站中各文章的第一张图片的代码示例,_PHP教程

PHP获取网站中各文章的第一张图片的代码示例,_PHP教程

WBOY
WBOYOriginal
2016-07-12 08:50:30834Durchsuche

PHP获取网站中各文章的第一张图片的代码示例,

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

以上代码默认调用文章首张图片,当文章没有图片的时候,随机调用主题style/images/random/下的1.jpg、2.jpg、3.jpg、4.jpg图片。如果不想调用随机图片,可以修改一下:

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

调用文章首张图片,如果文章没有图片就调用默认图片no-image.jpg

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1133119.htmlTechArticlePHP获取网站中各文章的第一张图片的代码示例, php $temp=mt_rand(1,4); $pattern="/[img|IMG].*src=[\'|\"](.*(:[\.gif|\.jpg|\.png]))[\'|\"].*[\/]/"; $content = $arti...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn