tags:

views:

1649

answers:

4

In PHP, replace one URL with another within a string e.g.

New post on the site <a href="http://stackoverflow.com/xyz1"&gt;http://stackoverflow.com/xyz1&lt;/a&gt;&lt;/p&gt;

becomes:

New post on the site <a href="http://yahoo.com/abc1"&gt;http://yahoo.com/abc1&lt;/a&gt;&lt;/p&gt;

Must work for repeating strings as above. Appreciate this is simple but struggling!

+1  A: 

Use str_replace():

$text = str_replace('http://stackoverflow.com/xyz1', 'http://yahoo.com/abc1', $text);

That will replace the first URL with the second URL in $text.

yjerem
A: 

Try this:

preg_replace('#(https?://)(www\.)?stackoverflow.com\b#', '\1\2yahoo.com', $text);

If you want to change the path after the url, add another group and use preg_replace_callabck. More information in the PHP documentation.

Armin Ronacher
A: 

Can you give a better example of what you're looking for? Would str_replace do what you want, or perhaps preg_replace?

nickf
Wanting to extract a shorturl and replace it with the longurl e.g. http://tinyurl.com/x1x1x to http://www.yahoo.com/news/abc001. Already figured how to resolve the longname from the short. Just need to extract the shorturl in the first place. Thanks
A: 
function replace_url($text, $newurl) {
    $text = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', $newurl, $text);
    return $text;
}

Should work. Regex stolen from here. This will replace all URLs in the string with the new one.

William Keller