抓出文章中的 image tag
  • 3,662 views,
  • 2013-09-03,
  • 上傳者: Kuann Hung,
  •  0
73e39f11bbe5e86d37181a790230e229.jpg
 

為了要支援 facebook 的 open graph,所以在 <head> 中都會加上相對應的 og tag。

但如果是讓 User 自己撰寫文章的情況,則指定 og:image 就會比較麻煩。以下提供一個 function 可以抓出文章中的 image

function GetImgFromHTML($html) 
{
    if (stripos($html, '<img') !== false) 
    {
        $imgsrc_regex = '#<\s*img [^\>]*src\s*=\s*(["\'])(.*?)\1#im';
        preg_match($imgsrc_regex, $html, $matches);
        unset($imgsrc_regex);
        unset($html);
        if (is_array($matches) && !empty($matches)) 
            return str_replace(' ', '%20', trim($matches[2]));
        else
            return false;
         
    } else
        return false;
}
 

只要回傳值不是 false 就是文章中第一個出現的 image tag 了!

 
  •  
Facebook 討論區載入中...
資料夾 :
標籤 :
發表時間 :
2013-09-03 17:24:12
觀看數 :
3,662
發表人 :
Kuann Hung
部門 :
老洪的 IT 學習系統
QR Code :