1

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.

10
  • 2
    /%2Cn%3A(\d+)&/ - regex101.com/r/mQ5dH4/1 Commented May 19, 2016 at 18:50
  • 1
    "I guess preg_match would be a better option than explode function in PHP." ...why is that? Commented May 19, 2016 at 18:53
  • For starters: echo urldecode('n%3A171717%2Cn%3A%747474%2Cn%3A555666%2Cn%3A1234567&bbn=555666'); Commented May 19, 2016 at 18:56
  • 1
    Where is this coming from? Much better ways to do it. Commented May 19, 2016 at 19:00
  • 1
    you can do this too /(\d+)(?=&bbn)/ Commented May 19, 2016 at 19:10

2 Answers 2

3

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]; 
Sign up to request clarification or add additional context in comments.

5 Comments

he wants 1234567 before &bbn,
@abracadaver you are right when you say there are many ways of doing this and this is an encoded url but a one liner regular expression would be very helpful.
You can't do it in one line because you have to retrieve something from the matches.
@izk: That's exactly what it does unless you move &bbn around somewhere else.
@AbraCadaver apologies misread the preg_match. Nice solution !
1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.