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

时间:2015-09-08 21:27:06

标签: php html regex url

我正在尝试从包含HTML的数据库列中提取包含www.domain.com的网址。正则表达式必须过滤掉www2.domain.com个实例和外部网址,例如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

如何修改我的Regex来完成此任务?

1 个答案:

答案 0 :(得分:3)

这是一种更安全的方法,可以提取包含a的{​​{1}} href属性值,其中键是XPath www.domain.com

'//a[contains(@href, "www.domain.com")]'

请参阅IDEONE demo,结果:

$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);

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

代码不言自明,XPath表达式只是意味着找到Array ( [0] => http://www.domain.com/test ) 属性包含<a> 的所有href标记。