Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-order regular expression matches

Tags:

regex

php

Is there a way to get the match patterns to change order? For example if you have a string with letters-digits and using preg_match_all(), and you want the resulting match array to have the digits before the letters. Is there a way to specify this in the regular expression itself?

So "aaa-111" would result in matches with

array(0 => '111', 1 => 'aaa');
like image 369
matthewdaniel Avatar asked Jun 25 '26 02:06

matthewdaniel


1 Answers

Perhaps named capture groups will help. Example:

preg_match('/(?<alphapart>[a-z]+)-(?<numpart>[0-9]+)/', 'aaa-111', $matches);

$matches:

array('alphapart' => 'asd', 'numpart' => '111')

This way you can refer to the matches by a name instead of whatever order index they were matched in.

Edit: Just for accuracy, I want to note that $matches will actually include the matches by index as well, so the actual $matches will be: array(5) { [0]=> string(7) "aaa-111" ["alphapart"]=> string(3) "aaa" [1]=> string(3) "aaa" ["numpart"]=> string(3) "111" [2]=> string(3) "111" }

like image 124
Jonathan Amend Avatar answered Jun 26 '26 17:06

Jonathan Amend



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!