tags:

views:

376

answers:

5

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.

+3  A: 

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;
}
Jonathan Sampson
+10  A: 

This is done by using parse_url:

$host = parse_url($domain, PHP_URL_HOST);
if($host == 'www.google.com') {
    // do something
}
Paolo Bergantino
You probably want more robust domain checking, as noted in Jonathan Sampson's answer.
Drew Stephens
How is a homemade regex more robust than a PHP built in?
Paolo Bergantino
A: 

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
A: 

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.

fiskfisk
A: 

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
Yeah I didn't see what you were trying there.
Paolo Bergantino