2

I need to take a variable that contains a URL, and check to see if the domain equals a certain domain, if it does, echo one variable, if not, echo another.

$domain = "http://www.google.com/docs";
if ($domain == google.com)
{ echo "yes"; }
else
{ echo "no"; }

Im not sure how to write the second line where it checks the domain to see if $domain contains the url in the if statement.

mrpatg
  • 10,001
  • 42
  • 110
  • 169

5 Answers5

15

This is done by using parse_url:

$host = parse_url($domain, PHP_URL_HOST);
if($host == 'www.google.com') {
    // do something
}
Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
7

Slightly more advanced domain-finding function.

$address = "http://www.google.com/apis/jquery";

if (get_domain($address) == "google.com") {
  print "Yes.";
}

function get_domain($url)
{
    $pieces = parse_url($url);
    $domain = isset($pieces['host']) ? $pieces['host'] : '';
    if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
        return $regs['domain'];
    }
    return false;
}
Sampson
  • 265,109
  • 74
  • 539
  • 565
2

In addition to the other answers you could use a regex, like this one which looks for google.com in the domain name

$domain = "http://www.google.com/docs";
if (preg_match('{^http://[\w\.]*google.com/}i', $domain))
{

}
Paul Dixon
  • 295,876
  • 54
  • 310
  • 348
1

Have you tried parse_url()?

Note that you might also want to explode() the resulting domain on '.', depending on exactly what you mean by 'domain'.

Bobby Jack
  • 15,689
  • 15
  • 65
  • 97
1

You can use the parse_url function to divide the URL into the separate parts (protocol/host/path/query string/etc). If you also want to allow www.google.com to be a synonym for google.com, you'll need to add an extra substring check (with substr) that makes sure that the latter part of the host matches the domain you're looking for.

MatsLindh
  • 49,529
  • 4
  • 53
  • 84