如何使用PHP和Regex提取特定域名的链接


How do I extract links with a specific domain name using PHP and Regex?

我试图从包含HTML的数据库列中提取包含www.domain.com的url。正则表达式必须过滤掉www2.domain.com实例和外部url,如www.domainxyz.com。它应该只搜索正确编码的锚链接。

到目前为止我写的是:

<?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.

我如何修改我的正则表达式来完成这个?

这里有一种更安全的方法来提取包含www.domain.coma href属性值,其中关键是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, result:

Array
(
    [0] => http://www.domain.com/test
)

如您所见,您也可以将DOMDocument和DOMXPath与字符串一起使用。

代码不言自明,XPath表达式仅表示查找所有具有包含www.domain.com href属性的<a>标记。