Make life easy.
function strip_apos($q) {
$q = str_replace("'","''",$q);
$q = str_replace("(''","('",$q);
$q = str_replace("'')","')",$q);
$q = str_replace("'',","',",$q);
$q = str_replace(",''",",'",$q);
return $q;
}
$query = strip_apos($query);
1) Replace all ' with ''
2) Reverse those that belong to the SQL itself. I.e. next to , commas and )( brackes.