How to check for certain values in url

2019-08-17 06:29发布

Is it possible to check if the url contains certain values, for instance if the URL "www.example.com/dummy1/dummy2/dummy3/en/dummy4/tim/" has an "en" or not.


Thanks

3条回答
戒情不戒烟
2楼-- · 2019-08-17 06:50

You can use the strpos function which is used to find the occurrence of one string inside other:

LIKE THIS

$url = 'www.example.com/dummy1/dummy2/dummy3/en/dummy4/tim/';

if (strpos($url,'en') !== false) {
    echo 'true';
}
查看更多
闹够了就滚
3楼-- · 2019-08-17 06:57
if (in_array('en', explode('/', $url))) { 
    ...
}
查看更多
Animai°情兽
4楼-- · 2019-08-17 07:06

The answers above may be what you're looking for, but in addition to searching for your value, here is how to actually retrieve the URL...

$url = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; //example.com/dummy1/dummy2/dummy3/en/dummy4/tim/
$url = $_SERVER['REQUEST_URI']; // /dummy1/dummy2/dummy3/en/dummy4/tim/

I'm assuming you want to know if a user is on a page that contains 'en' in which case you really don't need to check against the domain name, so you might do something like...

$contains_en = (strpos($_SERVER['REQUEST_URI'], 'en') !== false ? true : false);

you should note using strpos will also return true(actually it will return the match's start position in the string) if you have the character string en anywhere in the url, for example the word then would return true, so if you're looking for /en/ you can either use the in_array method described by other users to check, or simply check for the string '/en/' using this method

查看更多
登录 后发表回答