Replace whitespaces using PHP preg_replace function ignoring quoted strings

Posted by Saiful on Stack Overflow See other posts from Stack Overflow or by Saiful
Published on 2010-05-24T09:00:32Z Indexed on 2010/05/25 6:31 UTC
Read the original article Hit count: 264

Look at the following string:

SELECT
    column1 ,
    column2, column3
FROM
    table1
WHERE
    column1 = 'text, "FROM" \'from\\\' x' AND
    column2 = "sample text 'where' \"where\\\" " AND
    ( column3 = 5 )

I need to escape unnecessary white space characters from the string like:

  • removing white space from beginning and ending position of , ( ) etc
  • removing newline (\r\n) and tabs (\t)

But one thing. The remove process could not remove white spaces from the quoted string like:

  • 'text, "FROM" \'from\\' x'
  • "sample text 'where' \"where\\" "

etc.

i need to use the PHP function: preg_replace($pattern, $replacement, $string);

So what will be the value of $pattern and $replacement where the value of $string is the given SQL.

© Stack Overflow or respective owner

Related posts about php

Related posts about string