How to check a particular part of url using php

2019-06-10 18:01发布

问题:

I have a url in a variable.

<?php
$a='www.example.com';
?>

I have another variable, that has like this

<?php
$b='example.com';
?>

In what way I can check that $b and $a are same. I mean even if the url in $b is like

'example.com/test','example.com/test.html','www.example.com/example.html'

I need to check that $b is equal to $a in this case. If it is like example.net/example.org as the domain name changes, it should return false. I checked with strpos and strcmp. But I didn't find it is the correct way to check in case of urls.What function can I use to check that $b in this case is similar to $a?

回答1:

You could use parse_url for parsing the URL and get the root domain, like so:

  • Add http:// to the URL if not already exists
  • Get the hostname part of the URL using PHP_URL_HOST constant
  • explode the URL by a dot (.)
  • Get the last two chunks of the array using array_slice
  • Implode the result array to get the root domain

A little function I made (which is a modified version of my own answer here):

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;
}

Test cases:

$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";
    }
}

Output:

Root domain is the same
Root domain is the same
Root domain is the same
Not same
Not same

Note: This solution isn't foolproof and could fail for URLs like example.co.uk and you might want to additional checks to make sure that doesn't happen.

Demo!



回答2:

You can use parse_url to do the heavy lifting and then split the hostname by the dot, checking if the last two elements are the same:

$url1 = parse_url($url1);
$url2 = parse_url($url2);

$host_parts1 = explode(".", $url1["host"]);
$host_parts2 = explode(".", $url2["host"]);

if ($host_parts1[count($host_parts1)-1] == $host_parts2[count($host_parts2)-1] &&
   ($host_parts1[count($host_parts1)-2] == $host_parts2[count($host_parts2)-2]) {
   echo "match";
} else {
   echo "no match";
}


回答3:

I think that this answer can help: Searching partial strings PHP

Since these URLs are just strings anyway



标签: php url