chuuk chuuk - 5 months ago 29
PHP Question

Extracting TLD using PHP regex

I have an array of domain names formatted like this:

www.example.com
www.example.co.uk


from which I would like to extract the top-level TLDs, which would result in (respectively):

com
uk


To do this in PHP, I am using the regex:

preg_match("`(?<=\.)\w+$`", $cc, $tld_array);


This is meant to match the last
.
in a domain up to the end of the string. I expected this to give me

com
uk


as above, but instead only received

NULL
uk


Can anyone see why second-level TLDs are working while first-level TLDs don't?

RegExr suggests they should as well: http://regexr.com?31gsg

Answer

Posting here since a comment won't work for this:

php > $cc = 'www.example.com';
php > preg_match("`(?<=\.)\w+$`", $cc, $tld_array);
php > print_r($tld_array);
Array
(
    [0] => com
)

if this doesn't work for you, make sure that your example.com string doesn't have some non-printable chars hiding in it.