Angel M.
Angel M.

Reputation: 2732

replace link with another

I'm struggling on replacing text in each link.

$reg_ex = "/(http|https)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

$text = '<br /><p>this is a content with a link we are supposed to <a href="http://www.google.com">click</a></p><p>another - this is a content with a link we are supposed to <a href="http://www.amazon.com">click</a></p><p>another - this is a content with a link we are supposed to <a href="http://www.wow.com">click</a></p>';

if(preg_match_all($reg_ex, $text, $urls))
{

    foreach($urls[0] as $url)
    {

        echo $replace = str_replace($url,'http://www.sometext'.$url,  $text);
    }

}

From the code above, I'm getting 3x the same text, and the links are changed one by one: everytime is replaced only one link - because I use foreach, I know. But I don't know how to replace them all at once. Your help would be great!

Upvotes: 2

Views: 860

Answers (2)

JRomero
JRomero

Reputation: 4868

If you want the final variable to contain all replacements change it so something like this... You basically are not passing the replaced string back into the "subject". I assume that is what you are expecting since it's a bit difficult to understand the question.

$reg_ex = "/(http|https)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

$text = '<br /><p>this is a content with a link we are supposed to <a href="http://www.google.com">click</a></p><p>another - this is a content with a link we are supposed to <a href="http://www.amazon.com">click</a></p><p>another - this is a content with a link we are supposed to <a href="http://www.wow.com">click</a></p>';

if(preg_match_all($reg_ex, $text, $urls))
{
    $replace = $text;
    foreach($urls[0] as $url) {

        $replace = str_replace($url,'http://www.sometext'.$url,  $replace);
    }

    echo $replace;
}

Upvotes: 1

Marc B
Marc B

Reputation: 360572

You don't use regexes on html. use DOM instead. That being said, your bug is here:

$replace = str_replace(...., $text);
^^^^^^^^---                  ^^^^^---

you never update $text, so you continually trash the replacement on every iteration of the loop. You probably want

$text = str_replace(...., $text);

instead, so the changes "propagate"

Upvotes: 2

Related Questions