Page 1 of 1

problem with explode and double quotes

Posted: Sat Oct 10, 2009 5:32 am
by mariaalgarra
Hi all,

I have a problem with explode() when receivng a string which includes double quotes that I want to maintain.

I read a line ($line) from a file. $line contains the following:
dato1, dato2, "dato3.1,dato3.2", dato4

Then I realize the explode:
$regis= explode(",", $line);

If I print the result I obtain the following:
$regis[0]=dato1
$regis[1]=dato2
$regis[2]="dato3.1
$regis[3]=dato3.2"
$regis[4]=dato4

But what I really want to obtain is the following:
$regis[0]=dato1
$regis[1]=dato2
$regis[2]="dato3.1,dato3.2" (with or without double quotes, It doesnt matter)
$regis[3]=dato4

I cant change the comas as split character becuase this file is generated by other application.
Do you have any idea?

Thanks and regards.

Re: problem with explode and double quotes

Posted: Sat Oct 10, 2009 11:31 am
by JNettles
You're exploding separate values based upon the presence a comma, which it detects. To the explode function, it see's your " as part of value to include in the array.

You're going to need to search through your string for the presence of a quote marker, and then look for the second quote marker to complete the block. Use strstr to look for the quote markers. After you've stripped them out then you can do your normal explode.

Actually, in this case it might be better to look into using preg_split if you're comfortable with regular expressions. You'll be able to achieve this in far fewer lines of code if you do.

Re: problem with explode and double quotes

Posted: Sun Oct 11, 2009 5:43 am
by mariaalgarra
Thanks, finally I resolve with the fgetcsv()