PHP RegEx:以未知顺序匹配列表


PHP RegEx: match a list in an unknown order

我正在尝试匹配一些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函数。

有谁知道匹配所有可能的属性组合的方法吗?我确切地知道属性是什么,我只是不知道它们将以什么顺序出现。

说,我正试图找到一个更快的解决方案,而不是键入每个可能的组合并将其与|分开

一种非常不精确但又非常简单的方法是使用一个备选项列表:

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

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

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

是否存在一些顺序无关的单词

可以工作,这要感谢forward操作符(?=)。

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

或带注释

^            # 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

^前(?=。*对于效率非常重要!否则,引擎将对每个位置尝试搜索一次。

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