使用正则表达式在PHP中命名捕获

sat*_*ho 40 php regex

如何在PHP中使用带有正则表达式的命名捕获?谁能给我一个有效的例子?

Dre*_*lon 42

不适用于替换,仅对PHP中的匹配有用

$test="yet another test";

preg_match('/(?P<word>t[^s]+)/',$test,$matches);

var_dump($matches['word']);
Run Code Online (Sandbox Code Playgroud)


Ale*_*ruk 17

根据文件

PHP 5.2.2引入了两种替代语法(?<name>pattern)(?'name'pattern)

所以你会得到相同的结果:

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

在3v4l.org上查看结果