Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Named capture in PHP using regex

Tags:

regex

php

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

like image 460
sataho Avatar asked Aug 07 '11 07:08

sataho


People also ask

What does capture mean in regex?

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.

How do I capture a number in regex?

\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.


2 Answers

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']); 
like image 193
Dreaded semicolon Avatar answered Oct 11 '22 02:10

Dreaded semicolon


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

like image 40
Alexander Yancharuk Avatar answered Oct 11 '22 03:10

Alexander Yancharuk