Bengali - 1 year ago 84
PHP Question

# PHP regular expression with nth occurrence

Here's a string:

n%3A171717%2Cn%3A%747474%2Cn%3A555666%2Cn%3A1234567&bbn=555666

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:

n:171717,n:t7474,n:555666,n:1234567&bbn=555666

So:

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];