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

标签 php html regex url

我正在尝试从包含 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/

相关文章:

html - 将图像置于另一图像之上

php - MYSQL子查询和正则表达式

php - SESSION 不记得 php

php - 捕获imagemagick的正确方法转换PHP exec中的错误

javascript - 基于调查 ID 的 Limesurvey 条件

javascript - anchor 标记的数据绑定(bind) href 属性

html - 我如何使这个导航菜单居中?

php - WP HTML 缩小类不起作用

regex - Powershell在具有特殊字符的数组中搜索字符串

php - WordPress wp_get_current_user() 不显示结果