Bengali Bengali - 2 years ago 137
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.

Answer Source

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]; 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download