phpregexslack

PHP And Regex - Handling POST Variables in Single Field


So I'm having some issues with Regex. I need to match all occurrences of

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

Slack Slash Commands use a method of POSTing data that requires string manipulation, as it takes all text after a command /example --property:value --other:value and sends it as:

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

I'm not very formidable with Regex, but I was able to come up with the following:

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

So this way, It handles anything like

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

I do need to trim the value after splitting to avoid extra white space between the commands, but that's easy enough to do.

The only place this fails is with the following:

--property:value-with-dashes

Since I'm catching X instances of ([^-]+), it's seeing the first - and terminating, so I wind up with

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

Essentially, instead of terminating at the first -, I need it to terminate at the first -- (i.e. the start of another command), but I'm not sure sure how to figure this out... I'm unsure of the terminology (negative look-ahead has come up a few times, but I'm not sure how to get that to work)


Solution

  • You may use this regex with a lookahead:

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

    RegEx Demo

    RegEx Details: