简体   繁体   English

PHP preg_match正则表达式用于匹配模式中的上一个组?

[英]PHP preg_match regex for matching a previous group in the pattern?

I saw this question in Stackoverflow but the answers didn't help. 我在Stackoverflow中看到了这个问题,但答案没有帮助。 Actually i need to reference to previous group in my regex pattern. 实际上,我需要在我的正则表达式模式中引用上一组。

  $s = "1:1";

  $p = "/([0-9]):\1/";
  echo preg_match($p, $s); // False

OR 要么

  $p = "/([0-9]):$1/";
  echo preg_match($p, $s); // False

Escape backslash 转义反斜杠

<?php
  $s = "1:1";
  $p = "/([0-9]):\\1/";
  echo preg_match($p, $s);
  // Output: 1

(all is written in comments, but anyway) (所有内容均写在评论中,但无论如何)

Strings in double quotes are interpreted by php. 用双引号引起来的字符串由php解释。 In this case \\1 turns into octal 1. To make slash you need escaped it by itself \\\\ . 在这种情况下,\\ 1变成八进制1。要使斜杠需要自己转义\\\\

Or you can use uninterpreted string in single quotes '/([0-9]):\\1/' 或者,您可以在单引号'/([0-9]):\\1/'使用未解释的字符串

直接使用$p = "/([0-9]):?1/";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM