查找特定域名并在字符串PHP中附加url
假设我有以下字符串:查找特定域名并在字符串PHP中附加url,php,Php,假设我有以下字符串: <?php $str = 'To subscribe go to <a href="http://foo.com/subscribe">Here</a>'; ?> 我要做的是在字符串中查找具有特定域名的url,本例中为“foo.com”,然后附加url 我想要完成的是: <?php $str = 'To subscribe go to <a href="http://foo.com/subscribe?p
<?php
$str = 'To subscribe go to <a href="http://foo.com/subscribe">Here</a>';
?>
我要做的是在字符串中查找具有特定域名的url,本例中为“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的domdocument
类来操作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"