使用 PHP 检查 URL 是否具有特定字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7118823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if URL has certain string with PHP
提问by pisoe
I would like to know if some word is present in the URL.
我想知道 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'.
例如,如果 URL 中包含单词 car,例如 www.domain.com/car/ 或 www.domain.com/car/audi/,它将回显“汽车存在”,如果没有任何内容,则回显“没有汽车” .
回答by digi
Try something like this. The first row builds your URL and the rest check if it contains the word "car".
尝试这样的事情。第一行构建您的 URL,其余部分检查它是否包含“汽车”一词。
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url,'car') !== false) {
echo 'Car exists.';
} else {
echo 'No cars.';
}
回答by Santi Nunez
I think the easiest way is:
我认为最简单的方法是:
if (strpos($_SERVER['REQUEST_URI'], "car") !== false){
// car found
}
回答by J0HN
$url = " www.domain.com/car/audi/";
if (strpos($url, "car")!==false){
echo "Car here";
}
else {
echo "No car here :(";
}
See strpos
manual
参见strpos
手册
回答by nobody
if( strpos( $url, $word ) !== false ) {
// Do something
}
回答by Shuhad zaman
worked for me with php
用 php 为我工作
if(strpos($_SERVER['REQUEST_URI'], 'shop.php') !== false){
echo 'url contains shop';
}
回答by Mathijs Segers
strstr didn't exist back then?
strstr 那时还不存在?
if(strstr($_SERVER['REQUEST_URI'], "car")) {
echo "car found";
}
This must be one of the easiest methods right?
这一定是最简单的方法之一吧?
回答by Jeff
回答by chris
You can try an .htaccess method similar to the concept of how wordpress works.
您可以尝试类似于 wordpress 工作原理的 .htaccess 方法。
Reference: http://monkeytooth.net/2010/12/htaccess-php-how-to-wordpress-slugs/
参考:http: //monkeytooth.net/2010/12/htaccess-php-how-to-wordpress-slugs/
But I'm not sure if thats what your looking for exactly per say..
但我不确定这是否正是你想要的。
回答by Richard Andrew Lee
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (!strpos($url,'car')) {
echo 'Car exists.';
} else {
echo 'No cars.';
}
This seems to work.
这似乎有效。
回答by Mikeys4u
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...
否则它应该以相反的方式报告......