I made the following PHP code to build a query based on user input, where they can choose the condition and the operator and the resulting query would be printed on their screen every time they added something to the query:
if (!isset($_SESSION['filter_'.$c])) { // if its the first filter inserted
if ($operator == "NOT") {
@$_SESSION['query_first_'.$c] = "NOT $selected_condition";
} else {
@$_SESSION['query_first_'.$c] = "$selected_condition";
}
}
if ($operator == "OR" || $operator == 'OR NOT' || $operator == 'AND' || $operator == 'AND NOT') {
@$current_filter = "$operator $selected_condition";
@$_SESSION['query_'.$c] = " " . @$_SESSION['query_'.$c] . @$current_filter;
}
@$write_first = $_SESSION['query_first_'.$c];
@$write_last = $_SESSION['query_'.$c];
$_SESSION['filter_'.$c] = @$write_first . @$write_last;
This is in a function that is called whenever the user adds another condition, keeping the session variables between calls.
the output would be something like
WHERE condition AND condition OR NOT condition AND condition OR condition OR condition
So, I wanted to add parenthesis around the OR parts.
WHERE condition AND (condition OR NOT condition) AND (condition OR condition OR condition)
The latest solution I thought of would’ve been encasing all of the occurences in parenthesis at the end, then when the function gets called, it would remove all parenthesis so it wouldn’t have duplicates.
With my limited knowledge of Regex, I only managed to come up with this:
(?<=(ANDs)(NOTs)*).+(?:ORs+).+(?=s+AND)
This doesn’t really work, the main issues being the 0 or more operator in that NOT making the search ignore it, and the fact that this can only detect a single segment.
I tried another solution as well, which would open the parenthesis when the user input used an OR operator and close it when it went back to AND. I hit a roadblock when it got to the regex as well, and I don’t have the code anymore.
I tried looking up solutions to those specific tiny Regex issues but I didn’t know what to look for, or how. The results I found weren’t great.