how can PHP change a URL

310 Views Asked by At

I am trying to use PHP to change all dynamic URLs inside a div to a different, static URL.

For example I have:

<div class="mydiv">
  <a href="http://oldsite.com/123">Title 123</a>
  <a href="http://oldsite.com/321">Title 321</a>
  <a href="http://oldsite.com/abc">Title abc</a>
  <a href="http://oldsite.com/cba">Title cba</a>
</div>

and I want to change them all to:

<div class="mydiv">
  <a href="http://newsite.com">Title 123</a>
  <a href="http://newsite.com">Title 321</a>
  <a href="http://newsite.com">Title abc</a>
  <a href="http://newsite.com">Title cba</a>
</div>

I understand that I could do this with htaccess, but would prefer to do it in PHP if its possible. Any ideas?

EDIT: The oldsite.com links were generated from an RSS feed and are being embedded onto the page. I want all the RSS title links to just send the user to the new site home page.

3

There are 3 best solutions below

0
On

PHP can replace a string with another string in your HTML output, yes, but this doesn't mean it's a good idea. This will appear to achieve exactly what you want on the surface, but break in subtle ways and (in the case of a website crawled by a search engine spider) it will break existing clients that expect URLs to remain the same location.

Instead of trying to outsmart HTTP with PHP just use HTTP to your advantage. If you have access to the server of oldsite.com and all the links for it must be redirected to the new server at newsite.com at the same URL paths, then use your web server to inform clients with an HTTP/1.0 301 Permanently Moved response and a Location: http://newsite.com/foo-bar-baz header.

This will inform ALL HTTP clients of your website that the old content can be found at the new address, and also inform the client to update it's bookmarks and to invalidate it's cached location and other stored information. mod_rewrite makes this absolutely trivial in Apache but if you absolutely must use PHP then as a last resort use it's header() function to send the same HTTP headers that mod_rewrite would.

1
On
<?php str_replace( 'http://oldsite.com/', 'http://newsite.com/', $content );?>

str_replace takes 3 parameters. The first is what you want to be changed (needle), the second is what you want it changed to, and the third is what you are looking in (haystack).

You could also use an inline ternary operator:

<?php($link==$old_link)? 'http://newsite.com/': 'http://oldsite.com/';?>
0
On

You can do that using regular expressions:

$content = preg_replace("|http://oldsite.com(/([^'"]*)?)?|msi", "http://newsite.com", $content);

This will change all URLs starting with http://oldsite.com to http://newsite.com.