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?
In regular expressions, a lookbehind matches an element if there is another specific element before it. A lookbehind has the following syntax: In this syntax, the pattern match X if there is Y before it. For example, suppose you want to match the number 900 not the number 1 in the following string:
Regex: / (?<=r)e / Please keep in mind that the item to match is e. The first structure is a lookbehind structure so regex notes whenever there will be an e match it will have to traceback and enter into lookbehind structure. Hence the regex engine will first start looking for an e from the start of string and will move from left to right.
The syntax of a negative lookbehind is / (?<!element)match / Where match is the item to match and element is the character, characters or group in regex which must not precede the match, to declare it a successful match. So if you want to avoid matching a token if a certain token precedes it you may use negative lookbehind.
Lookbehind means to check what is before your regex match while lookahead means checking what is after your match. And the presence or absence of an element before or after match item plays a role in declaring a match.
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).
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);
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With