Aryan G
Aryan G

Reputation: 1301

what is pattern for preg_match_all to get domain name?

I want get domain name from text, I can do easily for email but can't get for domain name. I used this code to get email address :

if (!empty($text)) {
  $res = preg_match_all(
    "/[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}/i",
    $text,
    $matches
  );
}

What is the pattern for get only domain name from text?

Upvotes: 0

Views: 3002

Answers (2)

Mario Lurig
Mario Lurig

Reputation: 792

When doing email address validation, the most robust RegEx can be found here: http://fightingforalostcause.net/misc/2006/compare-email-regex.php

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

//if you mean to get domain from any url then this works:
preg_match( '@^(?:http://)?([^/]+)@i', $text, $matches );
$host = $matches[1];

//if you mean to get domain from email address , then this should work
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/" , $email))
{
list($username,$domain)=split('@',$email);
echo "Domain is:'.$domain;

Hope this is helpful

Upvotes: 1

Related Questions