我试图从一个用PHP抓取的HTML页面中获取关键字。
因此,如果关键字标记看起来像这样:
<meta name="Keywords" content="MacUpdate, Mac Software, Macintosh Software, Mac Games, Macintosh Games, Apple, Macintosh, Software, iphone, ipod, Games, Demos, Shareware, Freeware, MP3, audio, sound, macster, napster, macintel, universal binary">我想要找回这个:
MacUpdate, Mac Software, Macintosh Software, Mac Games, Macintosh Games, Apple, Macintosh, Software, iphone, ipod, Games, Demos, Shareware, Freeware, MP3, audio, sound, macster, napster, macintel, universal binary我构造了一个正则表达式,但它不起作用。
(?i)^(<meta name=\"keywords\" content=\"(.*)\">)有什么想法吗?
发布于 2009-11-16 00:14:38
使用函数get_meta_tags();
Tutorial
发布于 2009-11-16 00:16:00
我会使用像DOMDocument和XPath这样的解析器从DOM中检索节点:
$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$keywords = $xpath->query('//meta[translate(normalize-space(@name), "KEYWORDS", "keywords")="keywords"]/@content');
foreach ($keywords as $keyword) {
echo $keyword->value;
}translate function似乎是必要的,因为PHP的XPath实现不知道lower-case function。
或者使用PHP进行过滤:
$metas = $xpath->query('//meta');
foreach ($metas as $meta) {
if ($meta->hasAttribute("name") && trim(strtolower($meta->getAttribute("name")))=='keywords' && $meta->hasAttribute("content")) {
echo $meta->getAttribute("content")->value;
}
}发布于 2012-11-07 04:17:50
停止使用正则表达式。它很慢,资源密集,而且不是很灵活。
如果您正在使用PHP编程,请查看http://simplehtmldom.sourceforge.net/ - SimpleDom的强大功能,它能够以一种非常简单的面向对象的方式为您提供所需的一切。
// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');
// Find all images
foreach($html->find('img') as $element)
echo $element->src . '<br>';
// Find all links
foreach($html->find('a') as $element)
echo $element->href . '<br>';另一个例子-
// Example
$html = str_get_html("<div>foo <b>bar</b></div>");
$e = $html->find("div", 0);
echo $e->tag; // Returns: " div"
echo $e->outertext; // Returns: " <div>foo <b>bar</b></div>"
echo $e->innertext; // Returns: " foo <b>bar</b>"
echo $e->plaintext; // Returns: " foo bar"https://stackoverflow.com/questions/1737881
复制相似问题