MySQL Help - Stripping a piece of a string

Soldato
Joined
18 Oct 2002
Posts
5,586
Location
Stone, Staffordshire
I'm looking to extract the domain extension from a table full of website addresses, can anyone give me some pointers.

Here are some possible permutations and the part I want to extract:

These should all return .co.uk


These should all return.com

These should be .com.au

Any pointers guys?
 
Associate
Joined
18 Sep 2003
Posts
903
If it were me, and I had to do it this way I would just create a lookup table of every extension then use that in a "like" query against my other table.


For example:
http://sqlfiddle.com/#!2/c949f/3/0

This ^.

The only proper way I can think of to do this is to store a list of extensions to reference against, since that's the only way of knowing whether you want to go one or two levels deep. If for some reason you can't add a new table and it has to be done in the SQL, then if you know all the extensions that might be there, you could construct an SQL with a list of extension and use string manipulation like this:

PHP:
select 
if(
reverse(left(reverse(domain),locate(".",reverse(domain)))) 
in 
(".com",".net",".org",".us"),
reverse(left(reverse(domain),locate(".",reverse(domain)))),
if(reverse(left(reverse(domain),locate(".",reverse(domain),locate(".",reverse(domain))+1))) 
in
 (".co.uk",".au.com", ".org.uk","gov.us"), reverse(left(reverse(domain),locate(".",reverse(domain),locate(".",reverse(domain))+1))),"unknown")

) as domain_extension from domain;

But it would be much better to just store the extensions somewhere.
 
Back
Top Bottom