要利用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;
- }
- //假如數(shù)據(jù)庫已打開,用$nr獲取數(shù)據(jù)庫中的新聞內(nèi)容
- $nr=$row_news["nr"];
- $aa=getpic($nr_a);
- if(!$aa){$aa="images/nopic.jpg";} //如果新聞中不存在圖片,用默認的nopic.jpg替換
再看一個函數(shù)相對比較復(fù)雜了
在做項目的時候,頁面的設(shè)計有時會留有文章特色圖像的位置,可是有時,這篇文章反而沒有上傳圖片,則在頁面中顯示的時候則是沒有圖片,樣式上很難看,如果單純是沒有上傳圖片選用默認圖片的時候,有時會引起一些誤解,則在考慮是不是先對這個文章圖片的問題細化處理,先判斷是否有上傳的圖片,如果有則顯示上傳的圖片,沒有則判斷內(nèi)容中是否有圖片,有則選取第一張圖片作為此處的特色圖片,如果連內(nèi)容中也沒有圖片的話,則在此處顯示默認圖片;
以下是關(guān)于選取文章中第一張圖片的代碼,代碼如下:
- $obj=M("News");
- $info=$obj->where('id=1')->find();
- //方法1*********
- $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]; //獲取的整個Img屬性
- } 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";
- } //如果新聞中不存在圖片,用默認的nopic.jpg替換 */
- echo $img_path;
- //*************88
- $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";
- } //如果新聞中不存在圖片,用默認的nopic.jpg替換 */
- echo $img_path;
新聞熱點
疑難解答