Last Updated: February 25, 2016
· psychoticmeow

Easy(ish) to read regular expressions

You can make your regular expressions a little easier to read and debug if you name your match groups.

The following expression could be used as a (very simple) way to parse emails:

preg_match('/^([^@]+)@(.+)$/', $your_email, $matches);

Normally you would reference the name part of the email as $matches[1], so if you wanted to make sure the email was parsed correctly you would use:

if (isset($matches[1], $matches[2]) { ...

But it would be nicer if your code explained itself, so instead use this expression:


And then in your code you would write:

if (isset($matches['name'], $matches['domain']) { ...

Which makes it obvious exactly what parts of the expression you're testing for.