用于检查URL是否包含特定路径的语句?

时间:2018-10-13 10:23:04

标签: php wordpress if-statement url path

是否存在if语句,可让我检查URL是否包含特定路径?

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

谢谢您的帮助!

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:1)

我建议使用is_singular,is_tax等WordPress功能。

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