php 正则表达式 $1、$2 等

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4534516/
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-25 13:21:23  来源:igfitidea点击:

Regex $1, $2, etc

phpregexvariables

提问by Waleed Khan

I've been trying to do some regex operations in PHP, and I'm not very skilled in this area. It seems that when I use a regex function like preg_replace on a string, I can access the regex-replaced strings by some sort of variables named $1, $2, and so on. What is this called and how can I use it?

我一直在尝试用 PHP 做一些正则表达式操作,我在这方面不是很熟练。似乎当我在字符串上使用像 preg_replace 这样的正则表达式函数时,我可以通过某种名为 $1、$2 等的变量访问被正则表达式替换的字符串。这叫什么,我该如何使用它?

回答by BoltClock

These are known in regex terminology as backreferences(more on that here). You use them to refer to capture groups (or subpatterns, surrounded by ()) within your regex or in the replacement string.

这些在正则表达式术语中称为反向引用(更多关于这里)。您可以使用它们来引用()正则表达式或替换字符串中的捕获组(或子模式,由 包围)。

An example:

一个例子:

/* 
 * Replaces abcd123 with 123abcd, or asdf789 with 789asdf.
 * 
 * The  here refers to the capture group ([a-z]+),
 * and the  refers to the capture group ([0-9]+).
 */
preg_replace('/([a-z]+)([0-9]+)/', '', $str);

回答by Orbling

They are called backreferences and match grouped elements within the regexp.

它们被称为反向引用并匹配正则表达式中的分组元素。

If you surround a section of the regexp with brackets, then you can refer to it in the replace section (or indeed later in the same regexp, by the backreference which corresponds to its position.

如果您用括号将正则表达式的一部分括起来,那么您可以在替换部分中引用它(或者实际上稍后在同一正则表达式中,通过与其位置相对应的反向引用。

Slash form, or dollar form can be used in replacements:

斜线形式或美元形式可用于替换:

,  == ,