I had multiple patterns (“=”,”<“,”>”,”!=”,”>=”,”<=”) that I needs to check for random strings supplied by user. I also needs to find the position of occurrence of this pattern.
User supplied string format will be like this
"Name ="
"Age >"
"date<="
Basically, I needs to separate the field name and these patterns, so it output like.
"Name" and "="
"Age" and ">"
"date" and "<="
Please not that there can be any number of spaces between field Name and age.
Right now, I am doing these, by first removing space and then matching for each
of patterns one by one using strpos and if matches, then I separate it by using
the position from strpos to get 2 substr.
Is there any better way to do this?
If your field name can’t containt special characters, which you use for patterns, it’s not very hard. Something like this should do the trick (might need a little testing before use):
This, however, will extract only the field name and pattern, this won’t tell you the “position” of the pattern.
P.S. To get a position, if you need it that badly, you can then use
$position = strpos($string, $matches[2]);And if you want to make sure user can only supply the patterns allowed, you can specify them manualy and expression will look something like this:
#([^=<>!]+)\s*(=|<|>|(!=)|(>=)|(<=))#