Check if URL has certain string with PHP

I would like to know if some word is present in the URL.

For example, if word car is in the URL, like www.domain.com/car/ or www.domain.com/car/audi/ it would echo 'car is exist' and if there's nothing it would echo 'no cars'.


Solution 1:

Try something like this. The first row builds your URL and the rest check if it contains the word "car".

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


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

Solution 2:

I think the easiest way is:

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

Solution 3:

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

See strpos manual

Solution 4:

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