Looking at your data, you don't want to explode on C; but on C;+linebreak. I don't know how wellformed your data is, so let's play it safe: remove spaces, search for all kinds of linebreaks and even something like
C;1;2;3;4;5;6;7
C; <- end_loop
C; <- end_loop
C;1;2;3;4;5;US
First be sure there is a linebreak at the end of the data, and add some kind of end of data sign (in this case the underscore _):
$str.= "\r\n_";
Now remove all spaces. And as I don't know what kind of linebreaks you use, replace all kinds of them by some other, easily recognizable character, like * and make sure there are no double linebreaks:
$str = str_replace (' ', '', $str); //remove all spaces
$str = str_replace (array('\r\n', '\n', '\r'), '*', $str); //replace all linebreaks
$str = str_replace ('**', '*', $str); //remove double linebreaks
then explode on C;*, being the end of a data-part:
$str= explode( 'C;*' , $str );
now for each part you can replace the ; and the * with a comma:
foreach($str as $v){
$new_str[] = str_replace (array( '*', ';' ), ',', $v) . 'C,';
}
One last thing to do as you will end up with an unwanted _C, at the end of your array:
end($new_str);
$key = key($new_str);
if($new_str[$key]=='_C,'){
unset($new_str[$key]);
}
Why the _ at the end of the file? To make sure you can seperate parts with only C; in the middle of your file, and the last one at the end of the file.
[edit]
Because the actual data differs from the sample given first, a revised answer.
$str.="\r\n_";
$str = str_replace (' ', '', $str);
$str = str_replace (array("\r\n", "\n", "\r"), '*', $str);
$str = str_replace ('**', '*', $str);
$str = str_replace ('C;*', '~~', $str);
$str = str_replace (';*', ';', $str);
$str = str_replace ('*', ';', $str);
$str= explode( '~~' , $str );
foreach($str as $v){
$new_str[] = str_replace (array( '*', ';' ), ',', $v) . 'C,';
}
end($new_str);
$key = key($new_str);
if($new_str[$key]=='_C,'){
unset($new_str[$key]);
}
C;in there, why do some "end the loop" and some don't?