JWH89
JWH89

Reputation: 53

PHP - Select part of a string between two characters

I've been doing research into this and I believe the answer is do to with regular expressions but I just can't get my head around them.

I have a number of strings and I need to select a number between two characters. Here is an example string

&user18339=18339,20070103,175439,pmt,793,A/3/1/2,335,793,A/3/1/2,

I need the number that occurs after A/3/1/2, and before the following ,

In this example I need to select 335. I can do this using explode however I run into problems when I need to get more than one number from a string, like in the example below.

Here is another example string

&user31097=31097,20070105,092612,pmt,4190,A/3/1/2,142,1162,A/3/1/1,22,2874,A/3/1/2,1046,4622,A/3/1/2,25,2872,A/3/1/2,

Again I need to get the numbers after the A/3/1/2, and before the following ,. So in this example I would want to take 142, 1046 and 25.

If anyone could let me know how to do this it would be greatly appreciated.

Upvotes: 4

Views: 2008

Answers (3)

codaddict
codaddict

Reputation: 455030

if(preg_match_all('#A/3/1/2,([^,]*),#',$str,$matches)) {                        
        // $matches[1] will have the required results.
}

See it in action

Upvotes: 1

rik
rik

Reputation: 8612

preg_match_all('/A\/3\/1\/2,([^,]+),/', $input, $matches = array());
print_r($matches);

Upvotes: 2

Poelinca Dorin
Poelinca Dorin

Reputation: 9703

$string = '&user31097=31097,20070105,092612,pmt,4190,A/3/1/2,142,1162,A/3/1/1,22,2874,A/3/1/2,1046,4622,A/3/1/2,25,2872,A/3/1/2,';
preg_match_all('/A\/3\/1\/2,([0-9]*?),/', $string, $matches);
var_dump($matches);

Upvotes: 3

Related Questions