note 32052 modified in function.explode by aidan

From: Date: Sun, 27 Jun 2004 14:27:03 +0000
Subject: note 32052 modified in function.explode by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-71924@lists.php.net to get a copy of this message
Here is a function that will read in either an array or one single string that is delimited (and/or has qualifiers) and return an array, segmenting out based on the delimiter. This works great with Microsoft Excel spreadsheets -> export to CSV file -> use this function to turn into an array (because explode(",",$array) does NOT work always). <?php function csv_explode($void, $delim = ",", $qual = "\"") { $final = array(); $string = ""; $bIsArray = false; if ( is_array($void) ) { $count = count($void); $bIsArray = true; } else //string $count = 1; for ( $i = 0; $i < $count; $i++ ) { if ( $bIsArray == true ) { $string = $void[$i]; } else $string = $void; $tstring = ""; $ccount = strlen($string); //*loop through a line for ( $k =0; $k < $ccount; $k++ ) { //*delimeter if ( $string[$k] == $delim ) { $final[] = trim($tstring); $tstring = ""; continue; } //*take care of qualifiers if ( $string[$k] == $qual ) { //*move us along until end qualifier $k++; do { if ( $string[$k] == $qual ) break; $tstring .= $string[$k]; $k++; } while ( $k < $ccount && $string[$k] != $qual ); $final[] = trim($tstring); $tstring = ""; continue; } $tstring .= $string[$k]; // add a char } // end inner for } // end outer for return $final; } ?> --was-- Here is a function that will read in either an array or one single string that is delimited (and/or has qualifiers) and return an array, segmenting out based on the delimiter. This works great with Microsoft Excel spreadsheets -> export to CSV file -> use this function to turn into an array (because explode(",",$array) does NOT work always). //*returns an array function csv_explode($void, $delim = ",", $qual = "\"") { $final = array(); $string = ""; $bIsArray = false; if ( is_array($void) ) { $count = count($void); $bIsArray = true; } else //string $count = 1; for ( $i = 0; $i < $count; $i++ ) { if ( $bIsArray == true ) { $string = $void[$i]; } else $string = $void; $tstring = ""; $ccount = strlen($string); //*loop through a line for ( $k =0; $k < $ccount; $k++ ) { //*delimeter if ( $string[$k] == $delim ) { $final[] = trim($tstring); $tstring = ""; continue; } //*take care of qualifiers if ( $string[$k] == $qual ) { //*move us along until end qualifier $k++; do { if ( $string[$k] == $qual ) break; $tstring .= $string[$k]; $k++; } while ( $k < $ccount && $string[$k] != $qual ); $final[] = trim($tstring); $tstring = ""; continue; } $tstring .= $string[$k]; // add a char } // end inner for } // end outer for return $final; } http://php.net/manual/en/function.explode.php

« previous php.notes (#71924) next »