2011-05-30 112 views
1

我需要一個函數在PHP中提取網站網址的描述,沒有元標記描述任何想法?在沒有元標記描述的網站中提取描述?

我曾嘗試這個功能,但不工作:

$content = file_get_contents($url); 

function getExcerpt($content) { 
    $text = html_entity_decode($content); 
    $excerpt = array(); 
    //match all tags 
    preg_match_all("|<[^>]+>(.*)]+>|", $text, $p, PREG_PATTERN_ORDER); 
    for ($x = 0; $x < sizeof($p[0]); $x++) { 
    if (preg_match('<p>i', $p[0][$x])) { 
     $strip = strip_tags($p[0][$x]); 
     if (preg_match("/\./", $strip)) 
     $excerpt[] = $strip; 
    } 
    if (isset($excerpt[0])){ 
     preg_match("/([^.]+.)/", $strip,$matches); 
     return $matches[1]; 
    } 
    } 
    return false; 
} 

$excerpt = getExcerpt($content); 
+0

你想要做什麼? 「提取描述」是什麼意思? – 2011-05-30 13:27:43

+0

@Pekka我想他試圖從沒有元描述的頁面中取出相關的文本片段。 – alexn 2011-05-30 13:30:57

+0

是的,如果網站沒有元標記說明,但我想提取一些文字來描述它 – grigione 2011-05-30 13:46:41

回答

2

Parsing HTML with RegEx幾乎總是一個壞主意。謝天謝地,PHP有一些庫可以爲你做好工作。下面的代碼使用DOMDocument來提取元描述,或者如果一個不存在,頁面中的前1000個字符。

<?php 
function getExcerpt($html) { 

    $dom = new DOMDocument(); 

    // Parse the inputted HTML into a DOM 
    $dom->loadHTML($html); 

    $metaTags = $dom->getElementsByTagName('meta'); 

    // Check for a meta description and return it if it exists 
    foreach ($metaTags as $metaTag) { 
     if ($metaTag->getAttribute('name') === "description") { 
      return $metaTag->getAttribute('content'); 
     } 
    } 

    // No meta description, extract an excerpt from the body 
    // Get the body node 
    $body = $dom->getElementsByTagName('body'); 
    $body = $body->item(0); 

    // extract the contents 
    $bodyText = $body->textContent; 

    // collapse any line breaks 
    $bodyText = preg_replace('/\s*\n\s*/', "\n", $bodyText); 
    // collapse any more leftover spaces or tabs to single spaces 
    $bodyText = preg_replace('/[ ]+/', ' ', $bodyText); 

    // return the first 1000 chars 
    return trim(substr($bodyText, 0, 1000)); 

} 

$html = file_get_contents('test.html'); 

echo nl2br(getExcerpt($html)); 

你可能會想多一點邏輯添加到它,一些DOM遍歷,試圖找到的內容,或文字的中部附近只是一些片斷。實際上,這段代碼可能會抓取一堆不需要的東西,如頁面導航的頂端等。

1

你應該先檢查是否有meta描述可用,如果是,則顯示其他搜索<p>標籤和顯示數據說明(您可能希望限制段落的長度,例如,如果長度小於30,則搜索下一段落)。如果沒有<p>標籤,那麼只需將標題顯示爲描述(這就是Facebook和Digg的工作原理)