簡體   English   中英

如何檢查網址中是否存在參數?

[英]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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM