功能废弃页面关键字,描述和标题?

时间:2012-06-15 03:30:19

标签: php regex web-scraping

我写了简单的3个函数来废弃简单html页面的标题,描述和关键字 这是第一个废除标题的功能

function getPageTitle ($url)
{
    $content = $url;
    if (eregi("<title>(.*)</title>", $content, $array)) {
        $title = $array[1];
        return $title;
    }
}

它工作正常 这些是废弃描述和关键字以及那些不起作用的两个功能

function getPageKeywords($url)
{
    $content = $url; 
    if ( preg_match('/<meta[\s]+[^>]*?name[\s]?=[\s\"\']+keywords[\s\"\']+content[\s]?=[\s\"\']+(.*?)[\"\']+.*?>/i', $content, $array)) { 
        $keywords = $array[1];  
        return $keywords; 
    }  
}
function getPageDesc($url)
{
    $content = $url; 
    if ( preg_match('/<meta[\s]+[^>]*?name[\s]?=[\s\"\']+description[\s\"\']+content[\s]?=[\s\"\']+(.*?)[\"\']+.*?>/i', $content, $array)) { 
        $desc = $array[1];  
        return $desc; 
    }  
}

我知道preg_match行可能有问题,但我真的不知道 我尝试了很多东西,但它不起作用

2 个答案:

答案 0 :(得分:2)

为什么不使用get_meta_tags? PHP Documentation Here

<?php
// Assuming the above tags are at www.example.com
$tags = get_meta_tags('http://www.example.com/');

// Notice how the keys are all lowercase now, and
// how . was replaced by _ in the key.
echo $tags['author'];       // name
echo $tags['keywords'];     // php documentation
echo $tags['description'];  // a php manual
echo $tags['geo_position']; // 49.33;-86.59
?>

注意您可以将参数更改为网址,本地文件或字符串。

答案 1 :(得分:1)

最好使用php的原生DOMDocument来解析HTML然后正则表达式,你也可以使用,在这一天的年龄分配网站甚至不添加关键字,描述标签不再,所以你不能依赖他们总是在那里。但是你可以使用DOMDocument来实现它:

<?php 
$source = file_get_contents('http://php.net');

$dom = new DOMDocument("1.0","UTF-8");
@$dom->loadHTML($source);
$dom->preserveWhiteSpace = false;

//Get Title
$title = $dom->getElementsByTagName('title')->item(0)->nodeValue;

$description = '';
$keywords = '';
foreach($dom->getElementsByTagName('meta') as $metas) {
    if($metas->getAttribute('name') =='description'){ $description = $metas->getAttribute('content'); }
    if($metas->getAttribute('name') =='keywords'){    $keywords = $metas->getAttribute('content');    }
}

print_r($title);
print_r($description);
print_r($keywords);
?> 
相关问题