2012-12-17 147 views
2

在多個模式的情況下,可能會返回preg_match在相同數組索引下的結果。我的意思是我有以下preg_match檢查不同子字符串('&q','?q','&keywords')的出現。php preg_match()多種模式

preg_match('/&q=(.+?)(&|$)|\?q=(.+?)(\&|$)|\&keywords=(.+?)(\&|$)/', urldecode($test_string), $matches); 

我想看到$matches[1]下所有出現的地方可以排除以下if聲明。

if($matches){ 
      if ($matches[1] != ''){ 
       $query_p = mysql_escape_string($matches[1]);  
      } elseif ($matches[3] != ''){ 
       $query_p = mysql_escape_string($matches[3]);  
      } elseif($matches[5] != ''){ 
       $query_p = mysql_escape_string($matches[5]); 
      } 
     } 
+1

這看起來像您試圖從url的查詢部分提取元素。有這方面的專門手段,你爲什麼要使用正則表達式? – arkascha

+0

是的,這將是想法,從url獲取查詢部分。你能指點我到正確的區域嗎? – fefe

+0

查看phps'parse_url()'函數並用'&'字符爆炸查詢結果部分:http://php.net/manual/en/function.parse-url.php – arkascha

回答

3

簡化您的正則表達式和轉換所有非intented捕獲組非捕獲組在您正則表達式是這樣的:

/[?&](?:q|keywords)=([^&]+)(?:&|$)/ 

或者使用parse_str函數來分析查詢字符串。

+0

謝謝!謝謝!! – fefe

+0

如果您從此答案中獲得解決方案,請將此答案標記爲已接受。 – joHN

+0

還有2分鐘 – fefe