Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if URL has certain string with PHP

Tags:

string

url

php

People also ask

How do you check if the URL contains a given string in PHP?

Method 1: strpos() Function: The strpos() function is used to find the first occurrence of a sub string in a string. If sub string exists then the function returns the starting index of the sub string else returns False if the sub string is not found in the string (URL).

How do I check if a URL contains a string?

Use indexOf() to Check if URL Contains a String When a URL contains a string, you can check for the string's existence using the indexOf method from String. prototype. indexOf() . Therefore, the argument of indexOf should be your search string.


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

I think the easiest way is:

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

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

See strpos manual


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