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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6971287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:43:19  来源:igfitidea点击:

Named capture in PHP using regex

phpregex

提问by sataho

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

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

回答by Dreaded semicolon

Doesn't work with replace , only useful for match in php

不适用于 replace ,仅对 php 中的匹配有用

$test="yet another test";

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

var_dump($matches['word']);

回答by Alexander Yancharuk

According documentation

根据文档

PHP 5.2.2 introduced two alternative syntaxes (?<name>pattern)and (?'name'pattern)

PHP 5.2.2 引入了两种替代语法(?<name>pattern)(?'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

在 3v4l.org 上查看结果