Bengali
Bengali

Reputation: 198

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.

Upvotes: 1

Views: 436

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

That looks like part of an encoded URL so there's 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]; 

Upvotes: 3

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

only %2Cn%3A will always be there in front of the numbers

urldecoded equivalent of %2Cn%3A is ,n:.
The last "enclosing boundary" &bbn remains as is.
preg_match function will do the job:

preg_match("/(?<=,n:)\d+(?=&bbn)/", urldecode("n%3A171717%2Cn%3A%747474%2Cn%3A555666%2Cn%3A1234567&bbn=555666"), $m);

print_r($m[0]);  // "1234567"

Upvotes: 1

Related Questions