如何检查url中是否存在参数


How to check for existence of parameter in url?

我想输出一条消息,只要url包含任何以p2开头的参数,例如在以下所有实例中:

example.com/?p2=hello

example.com/?p2foo=hello

example.com/?p2

example.com/?p2=

我试过:

if (!empty($GET['p2'])) {
    echo "a parameter that starts with p2 , is showing in your url address";
} else {
    echo "not showing";
}

这应该涵盖的所有情况

$filtered = array_filter(array_keys($_GET), function($k) {
    return strpos($k, 'p2') === 0;
});
if ( !empty($filtered) ) {
    echo 'a paramater that starts with p2 , is showing in your url address';
}
else {
    echo 'not showing';
}

只需在$_GET数组上迭代,并在匹配时为密钥添加一个以p2开头的条件即可执行所需操作。

foreach($_GET as $key=>$value){
    if (substr($key, 0, 2) === "p2"){
        // do your thing
        print $value;
    }
}

substr($key,0,2)从字符串中提取前两个字符

尝试

if (isset($GET['p2'])) {
echo "a paramater that starts with p2 , is showing in your url address";
} else {
echo "not showing";
}

最快的方法是

if(preg_match("/(^|'|)p2/",implode("|",array_keys($_GET)))){
    //do stuff
}