Check if URL has certain string with PHP

后端 未结 12 655
自闭症患者
自闭症患者 2020-11-30 17:19

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 \

相关标签:
12条回答
  • 2020-11-30 17:48

    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.';
    }
    
    0 讨论(0)
  • 2020-11-30 17:48

    Surely this is the correct way round....

    $url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
    
    
    if (!strpos($url,'mysql')) {
    echo 'No mysql.'; //swapped with other echo statement
    } else {
    echo 'Mysql exists.';
    }
    

    Otherwise its reporting the opposite way it should...

    0 讨论(0)
  • 2020-11-30 17:51

    This worked for me:

    // Check if URL contains the word "car" or "CAR"
       if (stripos($_SERVER['REQUEST_URI'], 'car' )!==false){
       echo "Car here";
       } else {
       echo "No car here";
       }
    
    If you want to use HTML in the echo, be sure to use ' ' instead of " ".
    I use this code to show an alert on my webpage https://geaskb.nl/ 
    where the URL contains the word "Omnik" 
    but hide the alert on pages that do not contain the word "Omnik" in the URL.

    Explanation stripos : https://www.php.net/manual/en/function.stripos

    0 讨论(0)
  • 2020-11-30 17:54

    Starting with PHP 8 (2020-11-24), you can use str_contains:

    if (str_contains('www.domain.com/car/', 'car')) {
       echo 'car is exist';
    } else {
       echo 'no cars';
    }
    
    0 讨论(0)
  • 2020-11-30 17:56

    I think the easiest way is:

    if (strpos($_SERVER['REQUEST_URI'], "car") !== false){
    // car found
    }
    
    0 讨论(0)
  • 2020-11-30 17:57
    if( strpos( $url, $word ) !== false ) {
        // Do something
    }
    
    0 讨论(0)
提交回复
热议问题