Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

PHP: preg_match Give Names to the Matches

DZone's Guide to

PHP: preg_match Give Names to the Matches

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

So Called – Subpatterns

In PHP 5.2.2+ you can name the sub patterns returned from preg_match with a specific syntax.

Named subpatterns now accept the syntax (?<name>) and (?’name’) as well as (?P<name>). Previous versions accepted only (?P<name>)

This is extremely helpful, when dealing with long patterns. As you may know you can simply use the “old school” way and to call the matches by their number based index:

    $haystack = '01 Jan 1970';
$pattern = '/(\d{1,2})\ (Jan|Feb)\ (19\d\d)/';

preg_match($pattern, $haystack, $matches);

print_r($matches);

Although it may look difficult to maintain, now you can simply name the sub patterns of preg_match and to call them with their associative array keys. This is more clear when writing code and it’s definitely more maintainable.

    $haystack = '01 Jan 1970';
$pattern = '/(?<day>\d{1,2})\ (?<month>Jan|Feb)\ (?<year>19\d\d)/';

preg_match($pattern, $haystack, $matches);

print_r($matches);

// now there's $matches['day'], $matches['month'] ...

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Published at DZone with permission of Stoimen Popov, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}