dlofrodloh dlofrodloh -5 years ago 112
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
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 Source

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


Array (
  [0] => orange fruit
  [1] => APPLE
  [2] => Kiwi
  [3] => banana pie
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download