如何使用正则表达式看后面?

时间:2012-01-12 15:33:02

标签: php regex

我有以下网址:www.exampe.com/id/1234,我想要一个获取id参数值的正则表达式,在本例中为1234

我试过

<?php
$url = "www.exampe.com/id/1234";
preg_match("/\d+(?<=id\/[\d])/",$url,$matches);
print_r($matches);
?>

并且Array ( [0] => 1 )只显示了第一个数字。

问题是,如何重写正则表达式以使用正面背后的所有数字?

2 个答案:

答案 0 :(得分:10)

为什么不只是preg_match('(id/(\d+))', $url, $matches)没有任何外观?结果将在$matches[1]

顺便说一下,正确的lookbehind表达式是((?<=id/)\d+),但除非你需要,否则你真的不应该使用lookbehind。

另一种选择是(id/\K\d+)\K重置匹配开始,通常用作更强大的外观)。

答案 1 :(得分:6)

我同意NikiC你不需要使用lookbehind;但既然你问 - 你可以写

<?php
$url = "www.exampe.com/id/1234";
preg_match("/(?<=id\/)\d+/",$url,$matches);
print_r($matches);
?>