Search code examples
phpregexpreg-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. 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

Solution

  • 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. In this case \1 turns into octal 1. To make slash you need escaped it by itself \\.

    Or you can use uninterpreted string in single quotes '/([0-9]):\1/'