thydzik
thydzik

Reputation: 165

PHP Regex get the second grouped match

I have the following example.

regex:

'/test=([0-9]*).*?marker/'

testing string:

test=1234 test=5678 unknown marker

the matched group returns:

1234

how do I modify the regex to return 5678, the closest value to the marker?

thanks

edit: I have updated the example. sorry for the confusion. where unknown can be anything

Upvotes: 2

Views: 628

Answers (2)

anubhava
anubhava

Reputation: 784998

Any of these 2 regex will work:

$s = 'test=1234 test=5678 unknown marker'; // input
if (preg_match('/test=(\d+)(?!.*?test=\d+)/', $s, $arr)) var_dump($arr[1]);
// OR
if (preg_match('/test=(\d+)\D*marker/', $s, $arr)) var_dump($arr[1]);

OUTPUT:

string(4) "5678"
string(4) "5678"

Upvotes: 0

elclanrs
elclanrs

Reputation: 94101

$str = 'test=1234 test=5678 marker';
preg_match('/test=(\d+)\smarker/', $str, $matches);
echo $matches[1]; //=> 5678

Upvotes: 1

Related Questions