Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to find content not in quotes

Tags:

regex

php

I'm trying to find parameters outside 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 produce the follow result,

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

And I want only:

:to_email
:ip_from
like image 889
Ragen Dazs Avatar asked Feb 01 '13 13:02

Ragen Dazs


3 Answers

'/^\\s*:[A-Za-z0-9_]*/m'

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

edit

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

This uses the passive non-capture group (?:) which puts the proper results, without the space padding into a sub array of the matches variable at index 1.

like image 58
Louis Ricci Avatar answered Oct 01 '22 16:10

Louis Ricci


You can use a negative look-behind. This way you will match exactly what's needed.

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

Demo

like image 43
Ja͢ck Avatar answered Oct 01 '22 15:10

Ja͢ck


What about this:

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

It's not very rigorous and might fail for more complex examples like like tennis scores (15 : 30) but is probably good enough for your needs.

like image 28
cha0site Avatar answered Oct 01 '22 15:10

cha0site