chuuk chuuk - 1 year ago 116
PHP Question

Extracting TLD using PHP regex

I have an array of domain names formatted like this:

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


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


as above, but instead only received


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

RegExr suggests they should as well:

Answer Source

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

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download