PHP正则表达式串联不必要的反斜杠

I'm trying to build a regular expression in php. I tested it here https://regex101.com/ and it works fine, but that was before I knew I'd have to implement it in php and it adds backslashes where not needed.

这是我的代码:

$datePattern        = "\[((19|20)\d\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])\]";
$tag                = "[a-z]+(?:-[a-z]+)*";
$regroupmentPattern = "\[($tag)?\]";
$taglistPattern     = "\[((?:$tag)?(?:;(?:$tag))*)\]";
$countryPattern     = "\[([a-z]{2})\]";
$freePattern        = "\[([^\[\]]*)\]";
$extensionPattern   = "\.(jpg|png)";
$repetitionPattern  = "(?:\(\d+\))?";

$fullPattern        = "/^$datePattern$regroupmentPattern$taglistPattern$countryPattern$freePattern$freePattern$extensionPattern$repetitionPattern$/";

这是我想要的:

^\[((19|20)\d\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])\]\[([a-z]+(?:-[a-z]+)*)?\]\[((?:[a-z]+(?:-[a-z]+)*)?(?:;(?:[a-z]+(?:-[a-z]+)*))*)\]\[([a-z]{2})\]\[([^\[\]]*)\]\[([^\[\]]*)\](?:\(\d+\))?\.(jpg|png)$

这就是我得到的:

"\"\\/^\\\\[((19|20)\\\\d\\\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])\\\\]\\\\[([a-z]+(?:-[a-z]+)*)?\\\\]\\\\[((?:[a-z]+(?:-[a-z]+)*)?(?:;(?:[a-z]+(?:-[a-z]+)*))*)\\\\]\\\\[([a-z]{2})\\\\]\\\\[([^\\\\[\\\\]]*)\\\\]\\\\[([^\\\\[\\\\]]*)\\\\]\\\\.(jpg|png)(?:\\\\(\\\\d+\\\\))?$\\/\""

我假设必须有某种转义函数,我尝试了preg_quote,但是它添加了更多的反斜杠。

顺便说一下,这是我的完整代码:

<?php
  class Gallery {
    // Name of the gallery, used to build folder path
    private $name;

    function __construct($name) {
      $this->name = $name;
    }

    /*
     * Returns the list of file names in a gallery folder,
     * or false if the folder doesn't exist
     */
      public function getFileNames() {
        $path = "../../gallery/$this->name";
        if (is_dir($path)) {
          $allFileNamesArray = scandir($path, SCANDIR_SORT_ASCENDING);
          $filteredFileNamesArray = array();

          // Building regular expression
          $datePattern        = "\[((19|20)\d\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])\]";
          $tag                = "[a-z]+(?:-[a-z]+)*";
          $regroupmentPattern = "\[($tag)?\]";
          $taglistPattern     = "\[((?:$tag)?(?:;(?:$tag))*)\]";
          $countryPattern     = "\[([a-z]{2})\]";
          $freePattern        = "\[([^\[\]]*)\]";
          $extensionPattern   = "\.(jpg|png)";
          $repetitionPattern  = "(?:\(\d+\))?";

          $fullPattern        = "/^$datePattern$regroupmentPattern$taglistPattern$countryPattern$freePattern$freePattern$extensionPattern$repetitionPattern$/";

          foreach ($allFileNamesArray as $fileName) {
            $matches = array();
            if (preg_match($fullPattern, $fileName, $matches, PREG_UNMATCHED_AS_NULL)) {
              $filteredFileNamesArray[] = $fileName;
            }
            var_dump($matches);
          }

          return json_encode($fullPattern);
        }
        else {
          return false;
        }
      }
  }
?>

(这里我出于调试目的返回了完整的Pattern而不是filteredFileNamesArray)

评论