Check whether URL match with Wildcard pattern

Suppose, you have some rules to check whitelisted url. So everytime whenever you will get a new url so you can cross match that URL with your whitelisted URL. And whitelisted URLs sometimes can be wildcard url. So to check whether the given URL matched any of the wildcard urls.

<?php
$whiteListedUrls = [
    "https://google.com/test/*",
    "https://yahoo.com/test/index.html",
    "https://sohelrana.me/*",
    "https://sohelrana.me"
];

$url = "https://google.com/test/testWildCard/ok.html";


function checkUrlWildcard($url, $whiteListUrls = [])
{
    foreach ($whiteListUrls as $wUrl) {
        $pattern = preg_quote($wUrl, '/');
        $pattern = str_replace('\*', '.*', $pattern);
        $matched = preg_match('/^' . $pattern . '$/i', $url);
        if ($matched > 0) {
            return true;
        }
    }

    return false;
}

//it will return true
var_export(checkUrlWildcard($url, $whiteListedUrls));

https://google.com/test/* this url means actually all url path after https://google.com/test/. So if we want to check https://google.com/test/testWildCard/ok.html whether it is covered with our rules or not. So it will return true of course.

It’s a simple PHP script. But may help somebody.

Shaharia is a professional software engineer with more than 10 years of experience in the relevant fields. Digital ad certified, cloud platform architect, Big data enthusiasts, tech early adopters.

Need PHP Expert?

I can be a great asset to your project
Request For Hire
close-link

Sharing is Awesome, Do It!

Share this post with your friends
close-link
Looking for a PHP expert? I can be a great help for your project.
Hire Me!
close-image