Named capture in PHP using regex

Viewed 33202

How can I use named capture with regex in PHP? Can anyone give me a working example?

2 Answers

According documentation

PHP 5.2.2 introduced two alternative syntaxes (?<name>pattern) and (?'name'pattern)

So you'll get same result using:

<?php
preg_match('/(?P<test>.+)/', $string, $matches);  // basic syntax
preg_match('/(?<test>.+)/', $string, $matches);   // alternative
preg_match("/(?'test'.+)/", $string, $matches);   // alternative

Check result on 3v4l.org

Related