【问题标题】:PHP RegEx: match a list in an unknown orderPHP RegEx:以未知顺序匹配列表
【发布时间】:2011-12-31 21:57:23
【问题描述】:

我正在尝试匹配一些 CSS 属性。但是,我无法预测它们的顺序。

例子:

header p {
color:#f2f3ed;
background-color:#353535;
background-image: url(../images/dots.png);
}

不过,我也应该期待:

header p {
background-image: url(../images/dots.png);
background-color:#353535;
color:#f2f3ed;
}

以及这三个属性的任何其他组合。我们正在构建的 Web 应用程序只允许我访问 preg_match 函数。

有人知道一种方法来匹配所有可能的属性组合吗?我确切地知道这些属性将是什么,我只是不知道它们会按什么顺序排列。

也就是说,我正在尝试找到一个比输入所有可能的组合并用|分隔它更快的解决方案

【问题讨论】:

  • 你应该只在这里使用 CSS 解析器而不是正则表达式。
  • 从技术上讲,您也可以多次调用preg_match,为您希望匹配的每个属性一次,但如果这是需要维护或由其他人使用的代码,则解析器是最好的方法.
  • 我试图为此构建一个正则表达式,但它把我的面条放在前面,中间有很多匹配项。
  • 如果 preg_match_all 可用,您也可以使用它来迭代所有行。

标签: php regex


【解决方案1】:

超级不精确但也非常简单的方法是使用替代列表:

/  ( \s* color:#\w+; | \s* bbb:... | \s* ccc:... ){3}  /x

量词{3} 将确保存在三个备选方案,并且顺序无关紧要。

但它允许三个color: 属性匹配。您必须决定这是否足够重要,或者是否不太可能有人会在您的 CSS 声明中编写三个连续的 color: 语句。

【讨论】:

    【解决方案2】:

    Regex for existence of some words whose order doesn't matter

    这要归功于前瞻运算符 (?= )。

    /^(?=.*(?:color|background-color|background-image)\:.*?;).*/gm
    

    或与 cmets

    ^            # beggining of line
    (?=          # positive lookahead (true if pattern present after current position; in this case the beginning of current line)
      .*         # anything before the pattern we search for
      (?:color|background-color|background-image)\:      # match any of those 3 sequences followed by : char
      .*?;       # anything followed by ; but not looking beyond the first ; found
      )
    .*           # match the rest of the chars from where the (?= ) was found.
    /gmx         # MODIFIERS: global, multi-line, extended (for comments, ignores spaces and anything after #)
    

    你可以在这里试试:

    https://regex101.com/r/tX0hK3/1

    (?=.* 之前的 ^ 对效率非常重要! 否则引擎会为每个位置尝试一次搜索。

    结尾 .*(或 .+ 或 .++,所有格)只是为了匹配行,现在我们已经找到了正确的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多