我正试图编写一个脚本,从远程URL中抓取规范URL。我不是一个专业的开发人员,所以如果我的代码中有什么不好看的地方,任何解释都将(并且将)受到赞赏。
我想做的是要么寻找:
<meta property="og:url" content="http://www.my-canonical-url.com/is-here-and-look-no-dynamic-parameters-186.html" />
<link rel="canonical" href="http://www.another-canonical-url.com/is-here" />`
并从中提取URL。
到目前为止我的代码:
$content = file_get_contents($url);
$content = strtolower($content);
$content = preg_replace("'<style[^>]*>.*</style>'siU",'',$content); // strip js
$content = preg_replace("'<script[^>]*>.*</script>'siU",'',$content); // strip css
$split = explode("'n",$content); // Separate each line
foreach ($split as $k => $v) // For each line
{
if (strpos(' '.$v,'<meta') || strpos(' '.$v,'<link')) // If contains a <meta or <link
{
// Check with regex and if found, return what I need (the URL)
}
}
return $split_content;
我已经和regex斗争了几个小时,试图弄清楚如何做到这一点,但它似乎远远超出了我的知识范围。
有人知道我需要如何定义这个规则吗?另外,你觉得我的剧本还可以吗,或者还有改进的空间吗?
谢谢大家!
使用DOMDocument
可以获得属性和内容
$html = '<meta property="og:url" content="http://www.my-canonical-url.com/is-here-and-look-no-dynamic-parameters-186.html" />';
$dom = new DOMDocument;
$dom->loadHTML($html);
$attr = array();
foreach ($dom->getElementsByTagName('meta') as $meta) {
if ($meta->hasAttributes()) {
foreach ($meta->attributes as $attribute) {
$attr[$attribute->nodeName] = $attribute->nodeValue;
}
}
}
print_r($attr);
输出::
Array
(
[property] => og:url
[content] => http://www.my-canonical-url.com/is-here-and-look-no-dynamic-parameters-186.html
)
第二个URL与相同
$html = '<link rel="canonical" href="http://www.another-canonical-url.com/is-here" />';
$dom = new DOMDocument;
$dom->loadHTML($html);
$attr = array();
foreach ($dom->getElementsByTagName('link') as $link) {
if ($link->hasAttributes()) {
foreach ($link->attributes as $attribute) {
$attr[$attribute->nodeName] = $attribute->nodeValue;
}
}
}
print_r($attr);
输出::
Array
(
[rel] => canonical
[href] => http://www.another-canonical-url.com/is-here
)
考虑使用DOMDocument,只需将HTML加载到DOMDocument对象中并使用getElementsByTagName,然后循环结果,直到其中一个具有正确的属性。就像你在写Javascript一样。