Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.