skip to Main Content

I am want to know how a regular expression to get the com or co.uk in a domain name

$domain = abcde.co.uk;
$domain2 = abcde.com
    
$tdl = preg_replace('/^.*.([^.]+)$/D', '$1', $domain);
echo $tdl;

$tdl2 = preg_replace('/^.*.([^.]+)$/D', '$1', $domain);
echo $tdl2;

it works in the second but not the first.

2

Answers


  1. You could do substr($domain, strpos($domain, '.') + 1). Foolproof, and maybe more readable than a regular expression.

    Caveat: it only works if your string does contain a .

    Login or Signup to reply.
  2. This code will output whatever extension that comes after the first dot (using strpos() is a better practice, only use this code if you need it to be using Regex):

    $domain = "abcde.com";
    $tdl = preg_replace('/^[^.]+.(.*)$/', '$1', $domain);
    echo $tdl;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search