我正在尝试从包含 HTML 的数据库列中提取包含 www.domain.com
的 url。正则表达式必须过滤掉 www2.domain.com
实例和外部 url,如 www.domainxyz.com
。它应该只搜索正确编码的 anchor 链接。
这是我目前所拥有的:
<?php
$content = '<html>
<title>Random Website</title>
<body>
Click <a href="http://domainxyz.com">here</a> for foobar
Another site is http://www.domain.com
<a href="http://www.domain.com/test">Test 1</a>
<a href="http://www2.domain.com/test">Test 2</a>
<Strong>NOT A LINK</strong>
</body>
</html>';
$regex = "((https?)\:\/\/)?";
$regex .= "([a-z0-9-.]*)\.([a-z]{2,4})";
$regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?";
$regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?";
$regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?";
$regex .= "([www\.domain\.com])";
$matches = array(); //create array
$pattern = "/$regex/";
preg_match_all($pattern, $content, $matches);
print_r(array_values(array_unique($matches[0])));
echo "<br><br>";
echo implode("<br>", array_values(array_unique($matches[0])));
?>
我正在寻找这个以仅查找和输出 http://www.domain.com/test .
如何修改我的正则表达式来完成此操作?
最佳答案
这里有一个更安全的方法来提取 a
href
包含 www.domain.com
的属性值其中关键是 XPath '//a[contains(@href, "www.domain.com")]'
:
$html = "YOUR_HTML_STRING"; // Your HTML string
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$arr = array();
$links = $xpath->query('//a[contains(@href, "www.domain.com")]');
foreach($links as $link) {
array_push($arr, $link->getAttribute("href"));
}
print_r($arr);
参见 IDEONE demo ,结果:
Array
(
[0] => http://www.domain.com/test
)
如您所见,您也可以将 DOMDocument 和 DOMXPath 与字符串一起使用。
代码不言自明,XPath 表达式只是意味着查找所有<a>
具有 href
的标签包含 www.domain.com
的属性.
关于php - 如何使用 PHP 和 Regex 提取具有特定域名的链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32467524/