Jump to content

string replace probz


prashanth0626

Recommended Posts

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.. :(

 

Link to comment
https://forums.phpfreaks.com/topic/164087-string-replace-probz/
Share on other sites

...is it possible to replace to replace comma only outside the double quotes?

 

Here you go.

Example:

 

$str = <<<EOD
1,8,"name",4,10,"building , street, area"
2,4,"name",6,11,"building , street, area"
EOD;

function comma2pipe($a){
   return str_replace(',', '|', $a[0]);
}
$str = preg_replace_callback('#(?:^|")[^"]+"#', 'comma2pipe', $str);
echo nl2br($str);

Output:

1|8|"name"|4|10|"building , street, area"
2|4|"name"|6|11|"building , street, area"

Link to comment
https://forums.phpfreaks.com/topic/164087-string-replace-probz/#findComment-865601
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.