Quill Quill - 7 months ago 13
PHP Question

Better way of comparing substrings than a giant if loop

Alright so, in my code, I have a URL, and it gets passed into my function:

testURL($url)
, which, in order:


  1. Tests the
    base url
    whether it's the domain (
    'http://www.example.com'
    )

  2. Tests the various substrings:


    • ShowForum

    • Amex

    • Owners

    • ManagementCenter

    • WeatherUnderground

    • MapPopup

    • asp

    • pages


  3. Returns
    true
    if it has the
    base url
    , but doesn't match the substrings, otherwise
    return false;



Here's the code

function testURL($url){
if ((substr($url, 0, 23) == "http://www.example.com/") && (substr($url, 23, 3) != "asp") && (substr($url, 23, 4) != "Amex") && (substr($url, 23, 5) != "pages") && (substr($url, 23, 16) != "ManagementCenter") && (substr($url, 23, 16) != "Owners") && (substr($url, 23, 9) != "ShowForum") && (substr($url, 23, 8) != "MapPopup") && (substr($url, 23, 18) != "WeatherUnderground")) {
return false;
} else {
return true;
}


Example:

testURL('http://www.example.com/Amex'); --> returns true
testURL('http://www.example.com/PayPal'); --> returns false


It's called in my case like:

if (testURL('http://www.example.com/Visa')){
return;
}


The banned substrings list will get bigger as time goes on.
So, is there a better way to match substrings of variable lengths then that giant loop?

Thanks in advance!

Answer

This should work for you:

(Here I just parse the url with parse_url(), where then I check if the host matches and also if the path isn't in the array with in_array())

<?php

    function testURL($url) {
        $parsed = parse_url($url);
        if($parsed["host"] == "www.example.com" && !in_array(explode("/", $parsed["path"])[1], ["asp", "Amex", "WeatherUnderground", "MapPopup", "ShowForum", "Owners", "ManagementCenter", "pages"]))
            return false;
        else
            return true;
    }

?>
Comments