How to use Group Names in PHP preg_match() regex to index matched results by names instead of numeric values

Last updated on August 29th, 2020 at 09:33 am

Using regular expressions is a very effective way to find a sub-string or all matched sub-string from a given string or text. But when you call them they give you matched results in a array with numeric indexes which is not helpful enough to get your data out of the matched results. Following is the way to index matched results by name.

$input = 'theInput=%3Cdiv+class%3D%22%22%3E%0D%0A++++%3Ch1%3EXML+Escape+%2F+Unescape%3C%2Fh1%3E%0D%0A%3C%2Fdiv%3E&escapeXML=ESCAPE';
$matches = array();
preg_match('/theInput=(?P<theInput>[^&]*)/',$input,$matches);

So what we are doing here is naming the group using ?P<value> right at the beginning of the group where value is name of the index. Lets see the output

Array
(
[0] => theInput=%3Cdiv+class%3D%22%22%3E%0D%0A++++%3Ch1%3EXML+Escape+%2F+Unescape%3C%2Fh1%3E%0D%0A%3C%2Fdiv%3E
[theInput] => %3Cdiv+class%3D%22%22%3E%0D%0A++++%3Ch1%3EXML+Escape+%2F+Unescape%3C%2Fh1%3E%0D%0A%3C%2Fdiv%3E
[1] => %3Cdiv+class%3D%22%22%3E%0D%0A++++%3Ch1%3EXML+Escape+%2F+Unescape%3C%2Fh1%3E%0D%0A%3C%2Fdiv%3E
)

So as you can see now it will be easier to catch the result rather than numeric values right?

Leave a Reply

Your email address will not be published. Required fields are marked *