Php 无法匹配后续正则表达式模式
我需要从主字符串中提取以下字符串:Php 无法匹配后续正则表达式模式,php,regex,Php,Regex,我需要从主字符串中提取以下字符串: roundcube_sessauth=-del-;expires=周四,2015年8月6日03:38:33 GMT;路径=/;保护httponly roundcube_sessid=dh7a60r14c6qfa3lr7m90;路径=/;保护HttpOnly roundcube_sessauth=S2124929b7486e6805d615a86;路径=/;保护httponly 主要字符串是: roundcube_sessauth=-del-;expires=周
roundcube_sessauth=-del-;expires=周四,2015年8月6日03:38:33 GMT;路径=/;保护httponly
roundcube_sessid=dh7a60r14c6qfa3lr7m90;路径=/;保护HttpOnly
roundcube_sessauth=S2124929b7486e6805d615a86;路径=/;保护httponly
主要字符串是:
roundcube_sessauth=-del-;expires=周四,2015年8月6日03:38:33 GMT;路径=/;保护httponly,roundcube_sessid=dh7a60r14c6qfa3lr7m90;路径=/;保护HttpOnly,roundcube_sessauth=S2124929b7486e6805d615a86;路径=/;保护httponly
我的正则表达式是(roundcube.*httponly){1}
,它与第一个字符串完全匹配。但是,它与第二个或第三个匹配项不匹配,即(roundcube.*?httponly){2}
和(roundcube.*?httponly){3}
请让我知道我做错了什么。我正试图用PHP实现这一点 您显式地告诉正则表达式引擎仅用限制量词
{1}
匹配1次出现。移除它,正则表达式就会工作
此外,我建议使用单词边界使其更安全:
\broundcube.*?\bhttponly\b
请参阅(使用ignorecase选项!)
在PHP中,只是,而不是组
$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
修饰符,以便
也可以匹配换行符
(roundcube[\s\S]*?httponly)
您需要使
匹配换行符
或改用[\s\s]
。也使用i
标志。请参阅演示
我怀疑您是否需要
/m
选项,因为模式中没有^
或$
。无需使用[\s\s]
,它是PHP,支持/s
修饰符。此外,除非我们用正则表达式拆分字符串,否则将整个表达式封装在捕获组中是没有用的。那么/roundcube.*呢?httponly/I
@Uchiha:它也将在99,9%的时间内工作,IMHO。我只是添加了单词边界,以确保我们匹配roundcube
,而不是aroundcube
。顺便说一句,这就是为什么我写了删除它和正则表达式将工作。我指的是OP.Stribizev中的原始正则表达式,谢谢。完美的我已经忘记了组修改器!
$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);