Regex find content not in quotes

I'm trying to find options outside of quotes (Single ou Double)

$sql = " INSERT INTO Notifify (to_email, msg, date_log, from_email, ip_from) VALUES ( :to_email, 'test teste nonono', '2013-02-01 10:48:27', ' bar@foo ', :ip_from ) "; $matches = array(); preg_match_all('/:[A-Za-z0-9_]*/', $sql, $matches); 

The above code will give the following result:

print_r($matches); // array(:to_email, :48, :27, :ip_from)

And I want only:

 :to_email :ip_from 
+6
source share
3 answers
 '/^\\s*:[A-Za-z0-9_]*/m' 

Should do the trick, checking the beginning of the line and the space, and make sure the RegEx query is set to multi-line.

change

 preg_match_all('/(?:^\\s*)(:[A-Za-z0-9_]+)/m', $sql, $matches); print_r($matches[1]); 

In this case, a passive group without capture (? :) is used, which places the correct results without filling the gap in the auxiliary array of the matches variable in index 1.

+3
source

You can use a negative look. Thus, you will definitely agree with what you need.

 preg_match_all('/(?<!\w):[a-z0-9_]+/', $sql, $matches); 

Demo

+2
source

How about this:

 /\s+:[A-Za-z0-9_]*/ 

It is not very strict and may be unsuccessful for more complex examples, such as tennis scores ( 15 : 30 ), but is probably good enough for your needs.

+1
source

All Articles