Coder Perfect

PHP may be used to see if a URL contains a specific string.

Problem

I’d like to know if a specific word appears in the URL.

If the term car appears in the URL, such as www.domain.com/car/ or www.domain.com/car/audi/, it will echo ‘car exists,’ and if there are none, it will echo ‘no cars.’

Asked by pisoe

Solution #1

Try something along these lines. The first row creates your URL, and the subsequent rows verify that it contains the term “vehicle.”

$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];


if (strpos($url,'car') !== false) {
    echo 'Car exists.';
} else {
    echo 'No cars.';
}

Answered by digi

Solution #2

The simplest method, in my opinion, is:

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

Answered by santillanix

Solution #3

$url = " www.domain.com/car/audi/";
if (strpos($url, "car")!==false){
    echo "Car here";
}
else {
   echo "No car here :(";
}

See strpos manual

Answered by J0HN

Solution #4

if( strpos( $url, $word ) !== false ) {
    // Do something
}

Answered by nobody

Solution #5

I was able to get php to function for me.

if(strpos($_SERVER['REQUEST_URI'], 'shop.php') !== false){
echo 'url contains shop';
}

Answered by Shuhad zaman

Post is based on https://stackoverflow.com/questions/7118823/check-if-url-has-certain-string-with-php