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

时间:2015-12-08 12:15:25

标签: php

我想输出一条消息, 每当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";
}

4 个答案:

答案 0 :(得分:3)

这应该涵盖你的所有案件

$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';
}

答案 1 :(得分:1)

只需迭代$_GET数组,并在匹配时根据需要为p2添加键的条件。

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

substr($key,0,2)获取字符串

中的前两个字符

答案 2 :(得分:0)

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

} else {
echo "not showing";
}

答案 3 :(得分:0)

最快的方法是

[]