Using preg_replace (PHP) I want to remove all horizontal whitespace except for the whitespace found between quotes ("" and '') (including escaped quotes)
An example (regex should turn left side in right side):
2 + 2 => 2+2
f( " ") => f(" ")
f("Test \"mystring\" .") => f("Test \"mystring\" .")
f("' ", " ") => f("' "," ")
Using another post I came up with:
\h(?=[^']*(?:'[^']*'[^']*)*$)(?=[^"]*(?:"[^"]*"[^"]*)*$)
Which basically looks ahead and checks if there are an even amount of quotes until the end of the string (both "" and '').
However, I have problems with escaped characters and quotes inside quotes.
" ' test " => The ' causes problem
" \" test " => The \" causes problem
I have thought of using negative lookbehinds: (?<!\\)"
but can't get it to work. The next regex fails. It doesn't match when a string contains escaped quotes.
\h(?=[^"]*(?:(?<!\\)"(?:[^"]*?(?<!\\)")[^"]*?)*$)