I'm needing to parse some user inputs. They're coming to me in the form of clauses ex:
total>=100
name="foo"
bar!="baz"
I have a list of all of the available operators (<, >, <=, !=, = etc) and was using this to build a regex pattern.
My goal is to get each clause split into 3 pieces:
$result=["total", ">=", "100"]
$result=["name", "=", "foo"]
$result=["bar", "!=", "baz"]
My pattern takes all the operators and builds something like this (condensed for length)(this example only matches > and >=:
preg_split("/(?<=>)|(?=>)|(?<=>=)|(?=>=)/", $clause,3)
So a lookbehind and a lookahead for each operator. I had preg_split restrict to 3 groups in case a string contained an operator character (name="<wow>").
My regex works pretty great, however it fails terribly for any operator which includes characters in another operator. For example, >= is never split right because > is matched and split first. The same for != which is matched by =
Here's what I'm getting:
$result=["total", ">", "=100"]
$result=["bar", "!", "=baz"]
Is it possible to use regex to do what I'm attempting? I need to keep track of the operator and can't simply split the string on it (hence the lookahead/behind solution). One possiblity I considered would be to force a space or unusual character around all the operators so that > and >= would become, say, {>} and {>=} if the regex had to match the brackets, then it wouldn't be able to match early like it is now. However, this isn't an elegant solution and it seems like some of the regex masters here might know a better way.
Is regex the best solution or should I use string functions?
This question is somewhat similar, but I don't believe the answer's pseudocode is accurate - I couldn't get it to work well. How to manipulate and validate string containing conditions that will be evaluated by php
Aucun commentaire:
Enregistrer un commentaire