I got into a requirement to parse this type of input string to a where condition in laravel eloquent query
Input string:
apple or (orange and lime) or (cherry and "green apple")
Desired output:
where fruit = 'apple'
or ( fruit = 'orange' and fruit = 'lime')
or (fruit = 'cherry' and fruit = 'green apple')
I tried regex but didn't work out well.
It would be nice if some one can suggest to get this in array grouping, so that it can be reprocessed to query string
EDIT: SOLVED
$string = 'apple or (orange and lime) or (cherry and "green apple")';
$parts = preg_split('/("[^"]+"|\(|\)|\s+)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$sub_parts = array();
foreach ($parts as $part) {
if (preg_match('/\(|\)/', $part)) {
$sub_parts[] = $part;
} elseif (preg_match('/^"[^"]+"$/', $part)) {
$sub_parts[] = $part;
} else {
$sub_parts = array_merge($sub_parts, preg_split('/\s+/', $part, -1, PREG_SPLIT_NO_EMPTY));
}
}
//print_r($sub_parts);
$query = "WHERE ";
$word = '';
foreach ($sub_parts as $part) {
if($part == 'and' || $part == 'or' || $part == '(' || $part == ')') {
$query .= $part." ";
} else {
$query .= "fruit = '".str_replace('"', '', $part)."' ";
}
}
echo $query;
Output
WHERE fruit = 'apple' or ( fruit = 'orange' and fruit = 'lime' ) or ( fruit = 'cherry' and fruit = 'green apple' )