【问题标题】:Validate url parameters with preg_match使用 preg_match 验证 url 参数
【发布时间】:2018-11-29 18:50:30
【问题描述】:

有效示例

12[red,green],13[xs,xl,xxl,some other text with chars like _&-@#%]
number[anythingBut ()[]{},anythingBut ()[]{}](,number[anythingBut ()[]{},anythingBut ()[]{}]) or nothing


Full match 12[red,green]
Group 1 12
Group 2 red,green


Full match 13[xs,xl,xxl,some other text with chars like _&-@#%]
Group 1 13
Group 2 xs,xl,xxl,some other text with chars like _&-@#%

无效示例

13[xs,xl,xxl 9974-?ds12[dfgd,dfgd]]

我尝试的是:(\d+(?=\[))\[([^\(\[\{\}\]\)]+)\]regex101 link with what I tried,但这也匹配示例中给出的错误输入。

【问题讨论】:

  • 你对13[xs,xl,xxl 9974-?ds12[dfgd,dfgd]],12[red,green]有什么期望?
  • 不匹配(如果可能)或匹配正确语法的匹配 12[red,green]

标签: php regex validation url preg-match


【解决方案1】:
$in = '12[red,green],13[xs,xl,xxl,some other text with chars like _&-@#%],13[xs,xl,xxl 9974-?ds12[dfgd,dfgd]]';
preg_match_all('/(\d+)\[([^][{}()]+)(?=\](?:,|$))/', $in, $matches);
print_r($matches);

输出:

Array
(
    [0] => Array
        (
            [0] => 12[red,green
            [1] => 13[xs,xl,xxl,some other text with chars like _&-@#%
        )

    [1] => Array
        (
            [0] => 12
            [1] => 13
        )

    [2] => Array
        (
            [0] => red,green
            [1] => xs,xl,xxl,some other text with chars like _&-@#%
        )

)

说明:

/               : regex delimiter
  (\d+)         : group 1, 1 or more digits
  \[            : open square bracket
  (             : start group 2
    [^][{}()]+  : 1 or more any character that is not open or close parenthesis, brackets or square brackets
  )             : end group 2
  (?=           : positive lookahead, make sure we have after
    \]          : a close square bracket
    (?:,|$)     : non capture group, a comma or end of string
  )             : end group 2
/               : regex delimiter

【讨论】:

    【解决方案2】:

    如果只需要验证输入,可以添加一些锚点:

    ^(?:\d+\[[^\(\[\{\}\]\)]+\](?:,|$))+$
    

    Regex101

    如果您还需要获取所有匹配的部分,您可以使用另一个正则表达式。只使用一个效果不好。

    【讨论】:

      猜你喜欢
      • 2016-09-06
      • 1970-01-01
      • 2012-02-09
      • 1970-01-01
      • 1970-01-01
      • 2016-09-08
      • 2019-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多