检查URL是否具有PHP的特定字符串

pis*_*soe 99 php string url

我想知道URL中是否有某个单词.

例如,如果车载在URL中,例如www.domain.com/car/或www.domain.com/car/audi/,它就会回显"汽车存在",如果没有任何东西它会回应"没有汽车" .

小智 212

尝试这样的事情.第一行构建您的URL,其余部分检查它是否包含单词"car".

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


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


San*_*nez 63

我认为最简单的方法是:

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


J0H*_*0HN 21

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

strpos手册


nob*_*ody 11

if( strpos( $url, $word ) !== false ) {
    // Do something
}
Run Code Online (Sandbox Code Playgroud)


Shu*_*man 9

用PHP为我工作

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

  • 这与[这三个你的旧答案](/sf/answers/2021264171/)基本相同。为什么要发布这样的答案? (3认同)

Mar*_*ars 7

这对我有用:

// Check if URL contains the word "car" or "CAR"
   if (stripos($_SERVER['REQUEST_URI'], 'car' )!==false){
   echo "Car here";
   } else {
   echo "No car here";
   }
Run Code Online (Sandbox Code Playgroud)
如果要在回显中使用 HTML,请务必使用“ ”而不是“ ”。
我使用此代码在我的网页 https://geaskb.nl/ 上显示警报 
URL 包含单词“Omnik”的地方 
但在 URL 中不包含“Omnik”一词的页面上隐藏警报。

条带说明:https ://www.php.net/manual/en/function.stripos