⊗ppPmRgENP 256 of 447 menu

Named Capturing Groups Inside PHP Regex

Let's recall how we used capturing groups in the regular expression itself:

<?php $res = preg_replace('#([a-z])\1#', '!', $str); ?>

Sometimes there are situations when it is more convenient to refer to a group not by its number, but by its name. For this, we need to give the group a name:

<?php $res = preg_replace('#(?<letter>[a-z])#', '!', $str); ?>

Now we can refer to this group via the syntax \k<name>, like this:

<?php $res = preg_replace('#(?<letter>[a-z])\k<letter>#', '!', $str); ?>

The described named groups also have several alternative syntaxes: (?P=name), \k'name', \k{name}.

Given a string:

<?php $str = '12:59:59 12:59:12 09:45:09'; ?>

Find all substrings with time, in which the hour matches the seconds.

byenru