Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find specific domain name and append url in string PHP

Tags:

php

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.

like image 598
Matt J Avatar asked Jan 29 '26 17:01

Matt J


1 Answers

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:

  • The DOMDocument class
  • parse_url()
like image 104
Rajdeep Paul Avatar answered Jan 31 '26 06:01

Rajdeep Paul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!