php 獲取文章內(nèi)容的第一張圖片實例
來源:程序員人生 發(fā)布時間:2014-01-03 03:39:24 閱讀次數(shù):3568次
要利用php獲取文章中所有圖片中第一張圖片出來我們只需要簡單的正則表達式即可實現(xiàn)了,下面小編來給大家分享兩個實例吧。
首先看一個函數(shù),代碼如下:
- function getpic($str_img){
- preg_match_all("/<img.*>/isU",$str,$ereg);
- $img=$ereg[0][0];
- $p="#src=('|")(.*)('|")#isU";
- preg_match_all ($p, $img, $img1);
- $img_path =$img1[2][0];
- return $img_path;
- }
-
- $nr=$row_news["nr"];
- $aa=getpic($nr_a);
- if(!$aa){$aa="images/nopic.jpg";}
再看一個函數(shù)相對比較復(fù)雜了
在做項目的時候,頁面的設(shè)計有時會留有文章特色圖像的位置,可是有時,這篇文章反而沒有上傳圖片,則在頁面中顯示的時候則是沒有圖片,樣式上很難看,如果單純是沒有上傳圖片選用默認圖片的時候,有時會引起一些誤解,則在考慮是不是先對這個文章圖片的問題細化處理,先判斷是否有上傳的圖片,如果有則顯示上傳的圖片,沒有則判斷內(nèi)容中是否有圖片,有則選取第一張圖片作為此處的特色圖片,如果連內(nèi)容中也沒有圖片的話,則在此處顯示默認圖片;
以下是關(guān)于選取文章中第一張圖片的代碼,代碼如下:
- $obj=M("News");
- $info=$obj->where('id=1')->find();
-
- $soContent = $info['content'];
- $soImages = '~<img [^>]* />~';
- preg_match_all( $soImages, $soContent, $thePics );
- $allPics = count($thePics[0]);
- preg_match('/<img.+src="?(.+.(jpg|gif|bmp|bnp|png))"?.+>/i',$thePics[0][0],$match);
- dump($thePics);
- if( $allPics> 0 ){
- echo "<img src='".$match[1]."' title='".$match[1]."'>";
- }
- else {
- echo "沒有圖片";
- }
-
- $soContent = $info['content'];
- $soImages = '~<img [^>]* />~';
- preg_match_all( $soImages, $soContent, $thePics );
- $allPics = count($thePics[0]);
- dump($thePics);
- if( $allPics> 0 ){
- echo $thePics[0][0];
- } else {
- echo "沒有圖片";
- }
-
- $soImages = '~<img [^>]* />~';
- $str=$info['content'];
- preg_match_all($soImages,$str,$ereg);
- $img=$ereg[0][0];
- $p="#src=('|")(.*)('|")#isU";
- preg_match_all ($p, $img, $img1);
- $img_path =$img1[2][0];
- if(!$img_path){
- $img_path="images/nopic.jpg";
- }
- echo $img_path;
-
- $str=$info['content'];
- preg_match_all("/<img.*>/isU",$str,$ereg);
- $img=$ereg[0][0];
- $p="#src=('|")(.*)('|")#isU";
- preg_match_all ($p, $img, $img1);
- $img_path =$img1[2][0];
- if(!$img_path){
- $img_path="images/nopic.jpg";
- }
- echo $img_path;
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學習有所幫助,可以手機掃描二維碼進行捐贈