Bengali Bengali - 10 months ago 48
PHP Question

PHP regular expression with nth occurrence

Here's a string:


From this string how can I extract 1234567 ? Need a good logic / syntax.

I guess preg_match would be a better option than explode function in PHP.

It's about a PHP script that extracts data. The numbers can vary and the occurrence of numbers can vary as well only %2Cn%3A will always be there in front of the numbers.the end will always have a &bbn=anyNumber.


That looks like part of an encoded URL so there bound to be better ways to do it, but urldecoded() your string looks like:



preg_match_all('/n:(\d+)/', urldecode($string), $matches);
echo array_pop($matches[1]);

Parenthesized matches are in $matches[1] so just array_pop() to get the last element.

If &bbn= can be anywhere (except for at the beginning) then:

preg_match('/n:(\d+)&bbn=/', urldecode($string), $matches);
echo $matches[1];