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

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();

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

    [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?

Author: Tanmay Chakrabarty

Tanmay Chakrabarty is a former CSE student, currently working as a Senior Software Engineer with 5+ years of experience in the field of Web Application development in PHP+MySQL platform with strong skills in Javascript, JQuery, JQuery UI and CSS. He tries to write notes every week but fails due to heavy loads of duty.

Recommended Recommends


Contact Us