Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You could use <a href="http://php.net/parse_url" rel="nofollow noreferrer"><code>parse_url</code></a> for parsing the URL and get the root domain, like so:</p> <ul> <li>Add <code>http://</code> to the URL if not already exists</li> <li>Get the hostname part of the URL using <code>PHP_URL_HOST</code> constant</li> <li><a href="http://php.net/explode" rel="nofollow noreferrer"><code>explode</code></a> the URL by a dot (<code>.</code>)</li> <li>Get the last two chunks of the array using <a href="http://php.net/array_slice" rel="nofollow noreferrer"><code>array_slice</code></a></li> <li>Implode the result array to get the root domain</li> </ul> <p>A little function I made (which is a modified version of my own answer <a href="https://stackoverflow.com/a/18678205/1438393">here</a>):</p> <pre><code>function getRootDomain($url) { if (!preg_match("~^(?:f|ht)tps?://~i", $url)) { $url = "http://" . $url; } $domain = implode('.', array_slice(explode('.', parse_url($url, PHP_URL_HOST)), -2)); return $domain; } </code></pre> <p>Test cases:</p> <pre><code>$a = 'http://example.com'; $urls = array( 'example.com/test', 'example.com/test.html', 'www.example.com/example.html', 'example.net/foobar', 'example.org/bar' ); foreach ($urls as $url) { if(getRootDomain($url) == getRootDomain($a)) { echo "Root domain is the same\n"; } else { echo "Not same\n"; } } </code></pre> <p>Output:</p> <pre><code>Root domain is the same Root domain is the same Root domain is the same Not same Not same </code></pre> <p>Note: This solution isn't foolproof and could fail for URLs like <code>example.co.uk</code> and you might want to additional checks to make sure that doesn't happen.</p> <p><a href="https://eval.in/51335" rel="nofollow noreferrer"><strong>Demo!</strong></a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload