在没有元标记描述的网站中提取描述?

问题描述:

我需要一个函数在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

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遍历,试图找到的内容,或文字的中部附近只是一些片断。实际上,这段代码可能会抓取一堆不需要的东西,如页面导航的顶端等。

你应该先检查是否有meta描述可用,如果是,则显示其他搜索<p>标签和显示数据说明(您可能希望限制段落的长度,例如,如果长度小于30,则搜索下一段落)。如果没有<p>标签,那么只需将标题显示为描述(这就是Facebook和Digg的工作原理)