2

I have many strings like this:

parameter_1 >= '23' AND parameter_2 like 'cucurigu AND \picaso' AND parameter_3 IS NULL

And I want to make a preg_split() after every AND which is not inside apostrophes. The output of $matches should be an array with

0 => parameter_1 >= '23'
1 => parameter_2 like 'cucurigu AND \picaso'
2 => parameter_3 IS NULL

I don't know how to use it. I'm sure there is a simple solution to accomplish this with preg_split(). Unfortunately explode() can't do what I need. At the moment I have an enormous code which goes char by char and splits the string into an array like the one above. I need to update this big code to a small one because my task often changes.

P.S. If someone is willing to help me, add an explanation of the $pattern.

besciualex
  • 1,872
  • 1
  • 15
  • 20
  • Assuming you don't have escaped quotes: `'[^']*'(*SKIP)(*FAIL)|\s*AND\s*`. This doens't handle double quotes. You might want to clarify your question about above two cases... – HamZa Apr 20 '15 at 08:33

1 Answers1

4

Here you are, you can use the skip/fail PCRE trick, and only capture AND outside the single quotation marks:

'[^']*?'(*SKIP)(*F)|AND

See demo

The result:

Array                                                                                                                                                                                                                                                  
(                                                                                                                                                                                                                                                      
    [0] => parameter_1 >= '23'                                                                                                                                                                                                                         
    [1] =>  parameter_2 like 'cucurigu AND \picaso'                                                                                                                                                                                                    
    [2] =>  parameter_3 IS NULL                                                                                                                                                                                                                        
)

Explanation: We skip everything what is inside single quotes with '[^']*?'(*SKIP)(*F), and match AND in all contexts.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563