查找特定域名并在字符串PHP中附加url


Find specific domain name and append url in string PHP

假设我有以下字符串:

<?php
    $str = 'To subscribe go to <a href="http://foo.com/subscribe">Here</a>';
?>

我想做的是在字符串中找到具有特定域名的URLS,例如"foo.com",然后附加url。

我想要实现的目标:

<?php
    $str = 'To subscribe go to <a href="http://foo.com/subscribe?package=2">Here</a>';
?>

如果url中的域名不是foo.com,我不希望它们被附加。

您可以使用parse_url()函数和php的DomDoccument类来操作url,如下所示:

$str = 'To subscribe go to <a href="http://foo.com/subscribe">Here</a>';
$dom = new DomDocument();
$dom->loadHTML($str);
$urls = $dom->getElementsByTagName('a');
foreach ($urls as $url) {
    $href = $url->getAttribute('href');
    $components = parse_url($href);
    if($components['host'] == "foo.com"){
        $components['path'] .= "?package=2";
        $url->setAttribute('href', $components['scheme'] . "://" . $components['host'] . $components['path']);
    }
    $str = $dom->saveHtml();
}
echo $str;

输出:

To subscribe go to [Here]
                     ^ href="http://foo.com/subscribe?package=2"

以下是参考资料:

  • DOMDocument类
  • parse_url()