【问题标题】:Change a variable depending on value of url parameter根据 url 参数的值更改变量
【发布时间】:2018-10-30 01:01:09
【问题描述】:

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

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

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

我想要做的是检查值 2(文本字符串)是否仅在 custom_parameter 中存在,而不检查帖子 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!';
     }

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

任何想法如何使它正常工作?

【问题讨论】:

  • 可以直接使用参数$Get['pramtername'] 然后在上面做strpos

标签: php variables url-parameters


【解决方案1】:

可以单独查看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 并忽略 url

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

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

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

【讨论】:

  • 这听起来很棒。我对其进行了测试,但结果发现 Wordpress 无法识别自定义 url 参数:/
  • 事实证明您的解决方案有效。这是我的 nginx 配置文件中的错误配置。我错过了 /index.php?q=$uri&$args;谢谢!
  • @MartinPatzekov 很高兴它已排序:D
【解决方案2】:

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

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

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

【讨论】:

  • 感谢您的好主意。我对其进行了测试,但事实证明 Wordpress 无法识别自定义 url 参数。
  • 事实证明您的解决方案有效。这是我的 nginx 配置文件中的错误配置。我错过了 /index.php?q=$uri&$args;谢谢!
猜你喜欢
  • 2015-08-09
  • 1970-01-01
  • 2011-10-29
  • 2020-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-09
  • 2016-11-01
相关资源
最近更新 更多