Home » Php » php – How to use Regex look behind?

php – How to use Regex look behind?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have the following URL: www.exampe.com/id/1234 and I want a regex that gets the value of the id parameter which in this case is 1234.

I tried

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

and got Array ( [0] => 1 ) which is displaying the first digit only.

The question is, how do I rewrite the regex to get all the digits using positive look behind?

How to&Answers:

Why not just preg_match('(id/(\d+))', $url, $matches) without any lookbehind? The result will be in $matches[1].

By the way, the correct lookbehind expression would be ((?<=id/)\d+), but you really shouldn’t use lookbehind unless you need it.

Another alternative is (id/\K\d+) (\K resets the match start and is often used as a more powerful lookbehind).

Answer:

I agree with NikiC that you don’t need to use lookbehind; but since you ask — you can write

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