I am trying to find a good way of parsing SQL arguments, the way I am accomplishing it now seems like it can use a lot of improvement. I am trying to convert arguments that are split apart by ', & <= =>' from a string into SQL arguments like name = 'ABC' OR name ='John Doe'.
So
parseSQLOperators('dan,john&steven', 'username');
Will create
WHERE username= 'dan' OR username = 'john' AND username ='steven'
I have an example how this is being accomplished below but I am wondering if there is a better way for this. I know this code is ugly and I've been trying things like preg_splits but to no avail.
public static function parseSQLOperators($string, $content_term, $encapsulate = TRUE) {
$string = trim($string);
$length = strlen($string);
$ADD_PREFIX = true;
$output = '';
for ($i = 0; $i < $length; $i++) {
if ($string[$i] == '!') {
$output .= ' ' . $content_term . '!=\'';
if ($i == 0) {
$ADD_PREFIX = false;
}
} else if ($string[$i] == '+') {
if (@$string[$i + 1] != '!') {
$output .= ' AND ' . $content_term . '=\'';
} else {
$output .= ' AND ';
}
} else if ($string[$i] == ',') {
if (@$string[$i + 1] != '!') {
$output .= ' OR ' . $content_term . '=\'';
} else {
$output .= ' OR ';
}
}
if ($string[$i] != '!' && $string[$i] != '+' && $string[$i] != ',') {
$output .= $string[$i];
if (@$string[$i + 1] == ',' || @$string[$i + 1] == '+' || @$string[$i + 1] == '!' || $i == $length || $i == $length - 1) {
$output .= '\'';
}
}
}//end for
if ($ADD_PREFIX == true) {
$output = $content_term . '=\'' . $output;
}
if ($encapsulate) {
$output = '(' . $output . ')';
}
return $output;
}//end parseSQLOperator
dan,john&steven
becomes=dan | =john & =steven
? This has LOTS of advantages. First, you are using normal meanings for things.,
normally means and or union. I've never seen it meanor
. Secondly, it has a very specific structure:{comparator}{identifier}({operator}{comparator}{identifier})*
It's VERY easily parsed by a regular expression. \$\endgroup\$