PHP preg_match_all 正则表达式
如果我有一个像这样的字符串: 10/10/12/12
我正在使用:
$string = '10/10/12/12';
preg_match_all('/[0-9]+\/[0-9]+/', $string, $results);
这似乎只匹配 10/10
和 12/12< /代码>。我还想匹配
10/12
。是不是因为10/10
匹配后就从图片中删除了?那么在第一次匹配之后,它只会匹配 /12/12
中的内容?
如果我想匹配所有 10/10
、10/12
、12/12
,我的正则表达式应该是什么样子?谢谢。
编辑:我这样做了
$arr = explode('/', $string);
$count = count($arr) - 1;
$newarr = array();
for ($i = 0; $i < $count; $i++)
{
$newarr[] = $arr[$i].'/'.$arr[$i+1];
}
If I have a string like: 10/10/12/12
I'm using:
$string = '10/10/12/12';
preg_match_all('/[0-9]+\/[0-9]+/', $string, $results);
This only seems to match 10/10
, and 12/12
. I also want to match 10/12
. Is it because after the 10/10
is matched that is removed from the picture? So after the first match it'll only match things from /12/12
?
If I want to match all 10/10
, 10/12
, 12/12
, what should my regex look like? Thanks.
Edit: I did this
$arr = explode('/', $string);
$count = count($arr) - 1;
$newarr = array();
for ($i = 0; $i < $count; $i++)
{
$newarr[] = $arr[$i].'/'.$arr[$i+1];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议不要使用正则表达式。相反,您可以首先使用
explode
在斜杠上进行拆分。然后迭代这些部分,检查两个仅包含数字的连续部分。正则表达式不起作用的原因是匹配消耗了它匹配的字符。搜索下一场比赛从上一场比赛结束后的位置开始。
如果您确实想使用正则表达式,则可以使用零宽度匹配(例如前瞻)来避免消耗字符,并在前瞻中放置捕获匹配。
查看它在线运行:ideone
I'd advise not using regular expression. Instead you could for example first split on slash using
explode
. Then iterate over the parts, checking for two consecutive parts which both consist of only digits.The reason why your regular expression doesn't work is because the match consumes the characters it matches. Searching for the next match starts from just after where the previous match ended.
If you really want to use regular expressions you can use a zero-width match such as a lookahead to avoid consuming the characters, and put a capturing match inside the lookahead.
See it working online: ideone