2015-12-08 89 views
1

我要輸出一條消息, 每當鏈接包括與p2開始,例如,在以下所有實例的任何參數:如何檢查url中是否存在參數?

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"; 
} 
+0

的[檢查查詢字符串(PHP)](可能的複製http://stackoverflow.com/questions/1599193/check-query-string-php ) – brnrd

回答

0

嘗試

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

} else { 
echo "not showing"; 
} 
+0

他真的想抓到domain.com/?p2foo=hello你的例子沒有這樣做 –

+0

不工作...它返回'else',即使對於'p2 ='值 – rockyraw

+0

也btw isset($ GET ['p2'])&& $ GET ['p2']與!empty($ _ GET ['p2'])是相同的 –

0

最快的方法是

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

不起作用,它總是返回if條件,甚至for'?a = something' – rockyraw

+0

sry我的壞,我編輯它 –

+0

這也捕獲'ap2',我需要它只捕獲'p2a' :) – rockyraw

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'; 
} 
+0

這似乎工作,謝謝! – rockyraw

1

只是遍歷$_GET陣列,並添加一個條件爲關鍵從開始當匹配做你需要做的。

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

substr($key,0,2)從字符串採用的前兩個字符