problem with explode and double quotes

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mariaalgarra
Forum Newbie
Posts: 2
Joined: Sat Oct 10, 2009 5:25 am

problem with explode and double quotes

Post 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.
User avatar
JNettles
Forum Contributor
Posts: 228
Joined: Mon Oct 05, 2009 4:09 pm

Re: problem with explode and double quotes

Post 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.
mariaalgarra
Forum Newbie
Posts: 2
Joined: Sat Oct 10, 2009 5:25 am

Re: problem with explode and double quotes

Post by mariaalgarra »

Thanks, finally I resolve with the fgetcsv()
Post Reply