How can I use named capture with regex in PHP? Can anyone give me a working example?
capturing in regexps means indicating that you're interested not only in matching (which is finding strings of characters that match your regular expression), but you're also interested in using specific parts of the matched string later on.
\d for single or multiple digit numbers To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.
Doesn't work with replace , only useful for match in php
$test="yet another test"; preg_match('/(?P<word>t[^s]+)/',$test,$matches); var_dump($matches['word']);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With