
為了要支援 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 了!



