6

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
Ragen Dazs
  • 2,115
  • 3
  • 28
  • 56

3 Answers3

3
'/^\\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.

Louis Ricci
  • 20,804
  • 5
  • 48
  • 62
  • I cannot confirm this at all - is your `/m` supposed to be a modifier? Why is it enclosed in `'`'s? – h2ooooooo Feb 01 '13 at 13:48
  • @h2ooooooo - The m is the multiline modifier, the regex string starts and ends with /, the modifiers come after the last /. You could always go to http://sandbox.onlinephpfunctions.com/ to verify http://sandbox.onlinephpfunctions.com/code/9fd6ad6f70b771e44e6374525f3b2b735ccb89fa – Louis Ricci Feb 01 '13 at 14:00
  • @LastCoder I see - weirdly enough it didn't work in Regexr or Regex101. – h2ooooooo Feb 01 '13 at 14:24
2

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

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
1

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.

cha0site
  • 10,517
  • 3
  • 33
  • 51