How to use regex?

I have the following URL: www.exampe.com/id/1234, and I want the regular expression to get the id parameter value, 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 only displays the first digit.

The question is, how do I rewrite the regex to get all the numbers with a positive appearance?

+6
source share
2 answers

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

By the way, the correct lookbehind expression will be ((?<=id/)\d+) , but you really shouldn't use lookbehind if you don't need it.

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

+10
source

I agree with NikiC that you do not need to use lookbehind; but so how do you ask? You can write

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

Source: https://habr.com/ru/post/905836/


All Articles