0

I want to remove comma from string value of comma separated values.

I am parsing mysql insert queries for my project, and i am failing when string value contains comma.

I am working in php.

Example :

$temp = "INSERT INTO temp_table VALUES(1,'name','some random, address')";

as in above example, i want to remove the comma between some random and address.

Actually queries contains too many fields and complex values.

UPDATE

I hadn't mentioned my problem in depth, regrets.

I am reading from a mysql dump file, fetching insert queries in one array, then parsing each query.

SOLUTION

preg_replace("/,(?!(?:[^']*'[^']*')*[^']*$)/", '', $var_name);

will do the work, Thanks @Avinash Raj & @MarkusQ

Cœur
  • 37,241
  • 25
  • 195
  • 267
Gaurav Gandhi
  • 3,041
  • 2
  • 27
  • 40

2 Answers2

-1

First of all, you can use

 $string = str_replace(',', '', $string);

But in the example given, you are missing a closing ' before " and the query won't execute.

mariobgr
  • 2,143
  • 2
  • 16
  • 31
  • Then my all commas will be replaced, i jut want to remove comma between 'some random' and 'text' if referring example string. – Gaurav Gandhi Sep 09 '14 at 14:08
  • $string = str_replace('random,', 'random', $string); – mariobgr Sep 09 '14 at 14:09
  • But even better, you can use Prepared Statements to prevent this. – mariobgr Sep 09 '14 at 14:11
  • please at least consider my regex, it does actually match only the comma you want to replace. maybe a new export would be better, but sometimes a regex does the job too. – pauel Sep 09 '14 at 14:22
-2

If you have problems in your sql and there is no way of exporting again you could use a regular expression to improve the replacing.

$regex = '/(,)(?!\'.*\))/';

I suggest something like preg_replace($regex, '', "INSERT INTO temp_table VALUES(1,'name','some random, address')");

pauel
  • 908
  • 10
  • 26