比巨大的 if 循环更好的比较子字符串的方法

Better way of comparing substrings than a giant if loop

好吧,在我的代码中,我有一个 URL,它被传递到我的函数中:testURL($url),按顺序:

  1. 测试 base url 是否是域 ('http://www.example.com')
  2. 测试各种子串:

    • ShowForum
    • Amex
    • Owners
    • ManagementCenter
    • WeatherUnderground
    • MapPopup
    • asp
    • pages
  3. Returns true 如果有 base url 但不匹配子串,否则 return false;

这是代码

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

示例:

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

在我的例子中它被称为:

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

禁止的子串列表随着时间的推移变得越来越大。 那么,有没有比那个巨大的 循环更好的方法来匹配可变长度的子字符串?

提前致谢!

这应该适合你:

(这里我只是把url解析成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;
    }

?>