Alex Lord
asked on
extract word from url in php
https://www.facebook.com
how can i extract facebook from this url string in php ?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
http://static.ak.connect.facebook.com => Will match "ak"
http://facebook.com => Will not match at all
My own recommendation would be to first use parse_url to get the host, then use a regex to strip off the TLD (the ".com" and ".net" and ".co.uk", and so on), and then return the last piece of the hostname:
Open in new window
Note that the regex in my function is built off of the official TLD database:
http://data.iana.org/TLD/tlds-alpha-by-domain.txt
...but any country-level registrar has the ability to add their own second-level TLD (e.g. UK has the ".uk" extension, but they allow the ".co.uk" second-level TLD), so it's difficult to keep up with all of the possibilities there, so the regex above is sort of a "shotgun blast" approach that tries to match one or two of the words mentioned, so it will match "co" and then "uk" and mask it out. In that sense, it will match some variations that aren't truly valid TLDs and miss some, too (like the lawyer 2nd-level TLD in France), but it will get -most- of them right.