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.
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 atnewsite.com
at the same URL paths, then use your web server to inform clients with anHTTP/1.0 301 Permanently Moved
response and aLocation: 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'sheader()
function to send the same HTTP headers thatmod_rewrite
would.