PHP獲取網(wǎng)站中各文章的第一張圖片的代碼示例
更新時間:2016年05月20日 18:49:21 作者:china_skag
調(diào)取文章中的第一張圖作為列表頁縮略圖是很流行的做法,WordPress中一般主題默認(rèn)也是如此,那我們接下來就一起來看看PHP獲取網(wǎng)站中各文章的第一張圖片的代碼示例
<?php $temp=mt_rand(1,4); $pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/"; $content = $article->Content; //文章內(nèi)容 preg_match_all($pattern,$content,$matchContent); if(isset($matchContent[1][0])){ $temp=$matchContent[1][0]; }else{ $temp="images/random/$temp.jpg";//需要在相應(yīng)位置放置4張jpg的文件,名稱為1,2,3,4 } ?>
以上代碼默認(rèn)調(diào)用文章首張圖片,當(dāng)文章沒有圖片的時候,隨機(jī)調(diào)用主題style/images/random/下的1.jpg、2.jpg、3.jpg、4.jpg圖片。如果不想調(diào)用隨機(jī)圖片,可以修改一下:
<?php $pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/"; $content = $article->Content; //文章內(nèi)容 preg_match_all($pattern,$content,$matchContent); if(isset($matchContent[1][0])){ $temp=$matchContent[1][0]; }else{ $temp="./images/no-image.jpg";//在相應(yīng)位置放置一張命名為no-image的jpg圖片 } ?>
調(diào)用文章首張圖片,如果文章沒有圖片就調(diào)用默認(rèn)圖片no-image.jpg
相關(guān)文章
PHP中使用file_get_contents post數(shù)據(jù)代碼例子
這篇文章主要介紹了PHP中使用file_get_contents post數(shù)據(jù)代碼例子,本文直接給出代碼實例,需要的朋友可以參考下2015-02-02Zend Framework數(shù)據(jù)庫操作方法實例總結(jié)
這篇文章主要介紹了Zend Framework數(shù)據(jù)庫操作方法,結(jié)合實例形式總結(jié)分析了Zend Framework數(shù)據(jù)庫操作相關(guān)函數(shù)使用技巧與注意事項,需要的朋友可以參考下2016-12-12ThinkPHP利用PHPMailer實現(xiàn)郵件發(fā)送實現(xiàn)代碼
本文章介紹了關(guān)于在thinkphp中利用了phpmailer來實現(xiàn)郵件發(fā)送的詳細(xì)教程,有需要的朋友可以參考一下2013-09-09