Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Regex look behind?

Tags:

regex

php

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?

like image 337
Markel Mairs Avatar asked Jan 12 '12 15:01

Markel Mairs


People also ask

What is a look behind in regular expressions?

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:

How to use/regex?

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.

What is the syntax of negative look behind in regex?

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.

What is the difference between lookahead and lookbehind in regex?

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.


2 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).

like image 73
NikiC Avatar answered Sep 25 '22 10:09

NikiC


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);
?>
like image 38
ruakh Avatar answered Sep 25 '22 10:09

ruakh