3

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.

1

1 Answer 1

1

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:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.