dlofrodloh dlofrodloh - 5 months ago 18
PHP Question

Regex for getting multiple words separated by boolean operators

I have a string like:

$string='(orange fruit OR APPLE) AND (Kiwi OR banana pie)'


I need regex to extract the words separated by the boolean operators
OR
and
AND
and ignore the brackets.

So the result should be an array:
orange fruit, APPLE, Kiwi, banana pie


I'm not sure where to begin as I'm not very good with regex. Is there a simple way of doing this?

Answer

In your current case do the following:

$string =' ( orange fruit OR APPLE )  AND (Kiwi OR  banana pie)';
// Remove all extra characters and spaces from string
$result = trim(preg_replace('#[\s\(\)]+#', ' ', $string));
// Split result by possible delimeters
$result = preg_split('# (or|and) #i', $result);
// Output
print_r($result);

Output:

Array (
  [0] => orange fruit
  [1] => APPLE
  [2] => Kiwi
  [3] => banana pie
)