How can I use named capture with regex in PHP? Can anyone give me a working example?
3
-
6regular-expressions.info/named.htmlNullUserException– NullUserException2011-08-07 07:10:06 +00:00Commented Aug 7, 2011 at 7:10
-
Here is another reference: rexegg.com/regex-capture.html. I find this entire regex dedicated site to be an excellent resource. Especially this page: rexegg.com/regex-php.html, and this advanced technique page (skip to the end for the true shortcut trick) rexegg.com/regex-php.html.SherylHohman– SherylHohman2019-06-01 15:34:26 +00:00Commented Jun 1, 2019 at 15:34
-
@SherylHohman linked reference CSS is messed upkapreski– kapreski2020-04-25 03:19:48 +00:00Commented Apr 25, 2020 at 3:19
Add a comment
|
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']);
5 Comments
sataho
thanks. but what is t[^s]+ ?? consider i wanna find any thing between <tag> and </tag> into matches['word']. what i should do ?
Dreaded semicolon
[^s] =anything except letter s, I actually meant to write slash + s for space, but mistyped it but not important part. you could ask your other question in new one, maybe somebody will help you before me with that.
Howard
@sataho You can match anything between the tag using something like
/<tag>(?P<word>.*?)<\/tag>/.sataho
now if i want to do it with 2 tags using 1 regular exp . can I use it ? /<tag1>(?P<word>.*?)<\/tag1> <tag2>(?P<word>.*?)<\/tag2>/
Dreaded semicolon
no you can't do it like that. you need to read more about regular expression format: net.tutsplus.com/tutorials/javascript-ajax/…
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