Michael Watson
Michael Watson

Reputation: 1119

Regular expression / php to change url format

I have been given the task of updating a rather ugly, dated site, that has info on hundreds of cities, all of which sit on their own subdomain, for example:

london.sitedomain.com

The plan is to get rid of all these subdomains and set the site up properly as pages, in this format:

sitedomain.com/london

Unfortunately, there is a mass, hardcoded list making up a dropdown menu, looking something like this (but with hundreds):

<a href="http://sydney.sitedomain.com">Sydney</a>
<a href="http://auckland.sitedomain.com"> Auckland</a>
<a href="http://melbourne.sitedomain.com"> Melbourne</a>
<a href="http://perth.sitedomain.com"> Perth</a>
<a href="http://wellington.sitedomain.com"> Wellington</a>

If I set this huge list up as a php string, is there a decent way to change, in bulk, every subdomain substring into the correct format, as stated above? Or is there a better solution you can think of?

Upvotes: 0

Views: 215

Answers (4)

pcarvalho
pcarvalho

Reputation: 290

i suggest you go into a different route and automatize the process by using the reg exp in .htaccess. that way you don't need to even write that big list

something like this:

RewriteCond %{HTTP_HOST} ^((www\.)?[^.]+)\.sitedomain\.com.*$
RewriteRule (.*) http://sitedomain.com/%1 [L]

this will grab the www (if it has), then the subdomain and append the subdomain to the url

Upvotes: 0

joshhendo
joshhendo

Reputation: 2014

I think you'd be better off using a search and replace in a program like Notepad++ or Sublime Text. Both can do a regular expression search and replace of a folder (and subfolders.) I don't think PHP would be the best solution to this for a bunch of hard coded links (it could be done, but is much easier and more reliable this way.)

Use the following regular expression:

search:  http://(.*?)\.sitedomain.com
replace: http://sitedomain.com/\1

You could potentially do that in PHP with those search and replace fields, but if you just need to change a bunch of HTML files then I think using a text editor is much better.

Upvotes: 2

madfriend
madfriend

Reputation: 2430

If your links are dynamic (i.e. not hard-coded), change the way they are assigned to HTML template. The following should work:

$newurl = preg_replace("#(?:https?://)?(\w+)\.sitedomain\.com/(.*)#i", "sitedomain.com/$1/$2", $oldurl);

If your links are static, use any advanced text editor (Notepad++, Gedit, TextMate, etc.) and pick Search and Replace. First argument of preg_replace above is for Search field, second - for Replace.

Upvotes: 1

amitchhajer
amitchhajer

Reputation: 12830

one thing you can do is, explode and get the first string and append it with the remaining including the /

Upvotes: 0

Related Questions