根据url参数

时间:2018-05-20 00:47:59

标签: php variables url-parameters

是否有php方法根据url中某些参数的值更改php变量?

例如,我有这个特殊的网址:

http://example.com/post-url-that-contains-value2/?custom_parameter=value1-value2-value3

我想要做的是检查值2(文本字符串)是否仅在custom_parameter中退出而不检查post url(遗憾的是它包含与值2相同的字符串)。当我在custom_parameter中检查并找到值2时,将$ myphpvariable更改为特定值。

我正在做的是这样做:

$checkurl = $_SERVER['QUERY_STRING'];

if(preg_match('/^(?=.*custom_parameter)(?=.*value2).*$/m', $checkurl) === 1) {
     $myphpvariable = 'Found!';
     }

else {
     $myphpvariable = 'NOT Found!';
     }

不幸的是,此方法检查整个网址,即使在网址为$myphpvariable的情况下,它也会将'Found!'更改为http://example.com/post-url-that-contains-value2/?custom_parameter=value3,因为它会看到value2在帖子网址。

任何想法如何使这项工作正常?

2 个答案:

答案 0 :(得分:0)

您可以单独检查uri和参数

//explode the url on the ? and get the first part, the uri
$uri = explode('?', $_SERVER['REQUEST_URI'])[0];

//get everything in custom_parameter
$customParameter = $_GET['custom_parameter'];

//check value2 is in not in the uri and is in the params
if(strpos($uri, 'value2') === false && strpos($customParameter, 'value2') !== false){
    $myphpvariable = 'Found!';

}
else {
    $myphpvariable = 'NOT Found!';
}

或者您只是想检查custom_parameter并忽略网址

//get everything in custom_parameter
$customParameter = $_GET['custom_parameter'];

if(strpos($customParameter, 'value2') !== false){
    $myphpvariable = 'Found!';

}
else {
    $myphpvariable = 'NOT Found!';
}

答案 1 :(得分:0)

我只使用$_GET数组,而不是查看整个网址,因为它是自己访问查询字符串参数的最简单方法。

strpos()可能是使用$_GET数组搜索特定文本的最快捷最简单的方法,但您也可以使用类似的方法,因为您的值都由相同的分隔符分隔。这样,它会将custom_parameter char上的-值字符串拆分为一个数组,然后在该数组中搜索value2。如果您想稍后搜索其他值,这可能会更有用。

$customParamater = $_GET["custom_parameter"];
$values = explode("-",$customParamater);
if (in_array("value2",$values)) {
     $myphpvariable = 'Found!';
} else {
     $myphpvariable = 'NOT Found!';
}
相关问题