FilmJ
FilmJ

Reputation: 2011

Can you use preg_replace regexp with "not" condition?

I'm working with SQL strings, and need to replace "SELECT" with "SELECT SQL_CALC_FOUND_ROWS". Because I don't always know what the SQL is, there's potential that it will already have SQL_CALC_FOUND_ROWS so I need to account for that case, and not match in that case.

This is what I have so far:

preg_replace('/(^\s+SELECT)/i', 'SELECT SQL_CALC_FOUND_ROWS',$sql);

This will return: SELECT SQL_CALC_FOUND_ROWS * FROM table

FOR:

"\n SELECT * from table"

OR

"SELECT * from table"

I can do:

if (! stristr($sql,'SQL_CALC_FOUND_ROWS') ) { // do my replacement }

But is there a way to do this all in one preg_replace, and/or is it any faster (I expect this will be used quite extensively)?

Upvotes: 1

Views: 279

Answers (1)

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

You could use a negative lookahead:

/SELECT(?!\s+SQL_CALC_FOUND_ROWS)/

Upvotes: 2

Related Questions