Last Updated: February 25, 2016
·
900
· 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:

/^(?<name>[^@]+)@(?<domain>.+)$/

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.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

PHP applications still send a browser full of JavaScript. Hardening the server does not inventory the payment, analytics, and plugin scripts that run after the HTML is delivered.

Security insights from Cside