无法匹配后续正则表达式模式

时间:2015-08-06 07:03:38

标签: php regex

我需要从主字符串中提取以下字符串:

roundcube_sessauth=-del-; expires=Thu, 06-Aug-2015 03:38:33 GMT; path=/; secure; httponly

roundcube_sessid=dh7a60r14c6qfa3lr7m90; path=/; secure; HttpOnly

roundcube_sessauth=S2124929b7486e6805d615a86; path=/; secure; httponly

主要字符串是:

roundcube_sessauth=-del-; expires=Thu, 06-Aug-2015 03:38:33 GMT; path=/; secure; httponly, roundcube_sessid=dh7a60r14c6qfa3lr7m90; path=/; secure; HttpOnly, roundcube_sessauth=S2124929b7486e6805d615a86; path=/; secure; httponly

我的正则表达式是(roundcube.*?httponly){1},它与第一个字符串完全匹配。但是,它与第二次或第三次匹配不匹配,即(roundcube.*?httponly){2}(roundcube.*?httponly){3}

请让我知道我做错了什么。我试图在PHP中这样做。

2 个答案:

答案 0 :(得分:2)

您明确告诉正则表达式引擎仅将1次匹配与限制量词{1}匹配。删除它,正则表达式将工作。

另外,我建议用字边界使其更安全:

\broundcube.*?\bhttponly\b

请参阅demo(使用ignorecase选项!)

在PHP中,只是grab the matches,而不是群组。

$re = '/\broundcube.*?\bhttponly\b/i'; 
$str = "roundcube_sessauth=-del-; expires=Thu, 06-Aug-2015 03:38:33 GMT; path=/; secure; httponly, roundcube_sessid=dh7a60r14c6qfa3lr7m90; path=/; secure; HttpOnly, roundcube_sessauth=S2124929b7486e6805d615a86; path=/; secure; httponly"; 
preg_match_all($re, $str, $matches);
print_r($matches[0]);

如果您的输入中有换行符,请添加/s修饰符,以便.也可以匹配换行符号。

答案 1 :(得分:1)

(roundcube[\s\S]*?httponly)

您需要.匹配newlines或使用[\s\S]。请使用i标记。请参阅演示。

https://regex101.com/r/fM9lY3/22

$re = "/(roundcube[\\s\\S]*?httponly)/mi"; 
$str = "roundcube_sessauth=-del-; expires=Thu, 06-Aug-2015 03:38:33 GMT; path=/; secure; httponly, roundcube_sessid=dh7a60r14c6qfa3lr7m90; path=/; secure; HttpOnly, roundcube_sessauth=S2124929b7486e6805d615a86; path=/; secure; httponly"; 

preg_match_all($re, $str, $matches);