PHP 和正则表达式 - 处理单个字段中的 POST 变量

PHP And Regex - Handling POST Variables in Single Field

所以我在使用 Regex 时遇到了一些问题。我需要匹配所有出现的

--property:value --property:value ...

Slack Slash Commands 使用需要字符串操作的 POSTing 数据方法,因为它在命令 /example --property:value --other:value 之后获取所有文本并将其发送为:

text: --property:value --other:value

我对 Regex 不是很在行,但我能够想出以下内容:

--([^:=]+)([=]|[:])([^-]+)

所以这样,它可以处理

--property:value
--property:value with spaces
--property:value_with_underscores
--property=value
--property=value with spaces
--property=value_with_underscores
// etc etc

我确实需要 trim 拆分后的值以避免命令之间出现额外的白色 space,但这很容易做到。

唯一失败的地方是:

--property:value-with-dashes

因为我捕获了 ([^-]+) 的 X 个实例,它看到第一个 - 并终止,所以我结束了

--property:value // Missing `-with-dashes`, as invalid Match

本质上,我需要它在第一个 --(即另一个命令的开始)处终止,而不是在第一个 - 处终止,但我不确定如何解决这个问题......我不确定术语(负面前瞻已经出现过几次,但我不确定如何让它发挥作用)

您可以先行使用此正则表达式:

--([^:=]+)[:=](.*?)(?=\s+--|\z)

RegEx Demo

正则表达式详细信息:

  • --:匹配文字--
  • ([^:=]+):匹配1+个不是:=
  • 的字符
  • [:=]:匹配:=
  • (.*?): 匹配 0+ 个字符(惰性匹配)
  • (?=\s+--|\z):断言我们有 1+ 个空格后跟 -- 或前面的行尾