Let's say I have the following string:
<?php
$str = 'To subscribe go to <a href="http://foo.com/subscribe">Here</a>';
?>
What I'm trying to do is find the URLS within the string that have a specific domain name, "foo.com" for this example, then append the url.
What I want to accomplish:
<?php
$str = 'To subscribe go to <a href="http://foo.com/subscribe?package=2">Here</a>';
?>
If the domain name in the urls isn't foo.com, I don't want them to be appended.
You can use parse_url() function and the DomDoccument class of php to manipulate the urls, like this:
$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;
Output:
To subscribe go to [Here]
^ href="http://foo.com/subscribe?package=2"
Here are the references:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With