'Statement that checks whether a URL contains a particular path?

Is there an if statement that allows me to check whether a URL contains a particular path?

In my particular case (using wordpress), I'm trying to check wether the URL contains /store/ https://www.website.com.au/store/brand/ So there might be something after that path...

Thank you for your help!



Solution 1:[1]

I suggest using WordPress function like is_singular, is_tax, etc..

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

Solution 2:[2]

Use strpos() function. it basically finds the position of the first occurrence of a substring in a given string. If the substring is not found, it returns 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
}

Solution 3:[3]

Here is my simpler option to use if you don't want to create a function.

if( strpos( $_SERVER["REQUEST_URI"], "/store/" ) !== false ){ /* found */ }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Parsa
Solution 2 Madhur Bhaiya
Solution 3 Daniel Chase