Page 1 of 1

string replace probz

Posted: Mon Jun 29, 2009 7:20 am
by prashanth0626
hi
i have a long csv file
and it mostly consists of integer nd text data like dis

1,8,"name",4,10,"address"
2,4,"name",6,11,"address"
etc etc

nw i want to replace all comma with pipe symbol. but when i do this it replaces comma between address also.
so "building , street, area" also gets replaced to "building | street| area"
is it possible to replace to replace comma only outside the double quotes?
i load the entire csv file and then do preg replace.. :(

Re: string replace probz

Posted: Mon Jun 29, 2009 7:33 am
by prometheuzz
Up front: the "better" (more robust) solution would be to use a CSV parser to read and re-write the file.
That said, something like this would work:

Code: Select all

$text = '1,8,"name",4,10,"address, city"
2,4,"name",6,11,"address, foo, bar"
5,777,"f o, o",1116,10,"address, foo, bar"';
$text = preg_replace('/,(?=(?:[^"]*"[^"]*")*[^"]*$)/m', '|', $text);
echo $text;
Note that when you want to include quotes inside your string entries by escaping them with some character (like a backslash), my solution will break, and you'll have to adjust the proposed regex slightly (I leave that as an exercise for the reader! :twisted: ).