2012-12-17 166 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