【问题标题】:Statement that checks whether a URL contains a particular path?检查 URL 是否包含特定路径的语句?
【发布时间】:2019-03-18 09:59:39
【问题描述】:

是否有 if 语句可以让我检查 URL 是否包含特定路径?

在我的特殊情况下(使用 wordpress),我正在尝试检查 URL 是否包含 /store/ https://www.website.com.au/store/brand/ 所以在那条路径之后可能会有一些东西......

感谢您的帮助!

【问题讨论】:

    标签: php wordpress if-statement url path


    【解决方案1】:

    我建议使用 WordPress 函数,例如 is_singular、is_tax 等。

    function get_current_url()
    {
        $pageURL = 'http';
        if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
            $pageURL .= "s";
        }
        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "۸۰") {
            $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
        } else {
            $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        }
        return $pageURL;
    }
    
    $url = get_current_url();
    
    if (strpos($url, '/store/') !== false) {
        echo 'found';
    }else{
        echo 'not found';
    }
    

    【讨论】:

    • 非常感谢@Parsa!完美运行 :D 我正在研究 strpos() 但你帮助我在 wordpress 中理解它:)
    【解决方案2】:

    使用strpos() 函数。它基本上找到给定字符串中子字符串第一次出现的位置。如果未找到子字符串,则返回false

    // input url string
    $url = 'https://www.website.com.au/store/brand/';
    
    $path_to_check_for = '/store/';
    
    // check if /store/ is the url string
    if ( strpos($url, $path_to_check_for)  !== false ) {
    
        // Url contains the desired path string
        // your remaining code to do something in case path string is there
    
    } else {
    
        // Url does not contain the desired path string
        // your remaining code to do something in case path string is not there
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-14
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      • 2017-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多