note 47169 added to function.explode

From: Date: Fri, 05 Nov 2004 01:05:51 +0000
Subject: note 47169 added to function.explode
Groups: php.notes 
Request: Send a blank email to php-notes+get-80106@lists.php.net to get a copy of this message
I've found very useful the csv_explode function posted by ng4rrjanbiah at rediffmail dot com. THANKS! But, [ there is always a but d:o) ], it comes very handy to be able to skip the string delimiter with a backslash ("\"). Specially if you are using addslashes and stripslashes to create the CSV line. Here's my two cents: <?php // Explode CSV string function csv_explode($str, $delim = ',', $qual = "\"") { $skipchars = array( $qual, "\\" ); $len = strlen($str); $inside = false; $word = ''; for ($i = 0; $i < $len; ++$i) { if ($str[$i]==$delim && !$inside) { $out[] = $word; $word = ''; } else if ($inside && in_array($str[$i], $skipchars) && ($i<$len && $str[$i+1]==$qual)) { $word .= $qual; ++$i; } else if ($str[$i] == $qual) { $inside = !$inside; } else { $word .= $str[$i]; } } $out[] = $word; return $out; } // Test... $csv_str = 'a,"b",c,"this \"should\" work","and ""also"" this"'; echo "test: <pre>".print_r( csv_explode($csv_str), true )."</pre>"; ?> The result would be; test: Array ( [0] => a [1] => b [2] => c [3] => this "should" work [4] => and "also" this ) ---- Manual Page -- http://www.php.net/manual/en/function.explode.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+47169 Delete -- http://master.php.net/manage/user-notes.php?action=delete+47169&report=yes Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+47169&report=yes&reason=bad+code Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+47169&report=yes&reason=spam Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+47169&report=yes&reason=useless+example Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+47169&report=yes&reason=contains+commercial+links Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+47169&report=yes&reason=useless+note Reject -- http://master.php.net/manage/user-notes.php?action=reject+47169&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#80106) next »