Parsing lines from CSV files using Regular Expression
June 21, 2007 on 11:19 am | In PHP |Maybe I’m still a newbie at regular expressions, but I searched for a long time yesterday for something that actually works, failing with many code snippets that I found. I finally found something that actually works, so I am posting it here for the benefit of all.
Keep in mind that the challenging part is that commas inside quotations should not be treated as a delimiter, which seems to be where the challenge is coming from. I am posting this as a trackback to a blog post I found, because I am pretty much copying directly from there:
$expr = "/,(?=(?:[^\"]*\”[^\"]*\”)*(?![^\"]*\”))/”;Example:
$matches = preg_split($expr, '2006-01-01, "Apples, Oranges, and Pears", $5.95');
(In case it wasn’t already obvious, this works on a per-line basis. Break your CSV file into lines first.)
No Comments yet »
RSS feed for comments on this post. TrackBack URI
Leave a comment
You must be logged in to post a comment.
Powered by WordPress with Pool theme design by Borja Fernandez.
Entries and comments feeds.
Valid XHTML and CSS. ^Top^
Save in del.icio.us
StumbleUpon this