note 52231 deleted from function.explode by bjori

From: Date: Mon, 25 Sep 2006 08:09:50 +0000
Subject: note 52231 deleted from function.explode by bjori
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-117589@lists.php.net to get a copy of this message
Note Submitter: nsetzer at allspammustdie dot physics dot umd dot edu ---- Yet another "csv explode". It requires the nearest_neighbor function to work and that's handy in other situations as well. The code has the advantage (or disadvantage) of using strpos so that the PHP code doesn't transparently go through every character of the string. With very little modification this code could be used to allow the user to submit alternate deliminators that act like a ' or ". <?php function nearest_neighbor($individualGPS, $world, $races) { // find the nearest neighbor of each race foreach ($races as $ethnicGroup) $nearest[$ethnicGroup] = strpos($world, $ethnicGroup, $individualGPS + 1); // sort the nearest in ascending order asort($nearest, SORT_NUMERIC); reset($nearest); // get the first non-false foreach($nearest as $neighborRace => $neighborLocale) if ($neighborLocale !== FALSE) return array( 'char' => $neighborRace, 'str_loc' => $neighborLocale ); // went through all races and none are nearby return FALSE; } function csv_explode($explodeOn, $target) { // return FALSE if null string is the separator if ( empty($explodeOn) ) return FALSE; // set the search strings $spotlightArr = Array( $explodeOn, '"', "'"); $numExplosions = 0; $explodedStrArr[0] = $target; $currentLocale = 0; // start at the beginning // this loop doesn't have a conditional exit because it doesn't need one -- // either a nearest neighbor will be found, or it won't. while (TRUE) { // get the next reserved character and its position $nearest = nearest_neighbor($currentLocale, $target, $spotlightArr); if (! $nearest) return $explodedStrArr; switch (TRUE) { // <<<<<<<<<<<<<<<<<<<< BEGIN CASE ' or " >>>>>>>>>>>>>>>>>>>>>>>>>>> case ($nearest['char'] == '\''): case ($nearest['char'] == '"'): // in a string, find string end $nextStrChar = strpos($target, $nearest['char'], $nearest['str_loc'] + 1); if ($nextStrChar === FALSE) { // no closing string until end of $target so we're done return $explodedStrArr; } // change locale $currentLocale = $nextStrChar + 1; break; // <<<<<<<<<<<<<<<<<<<<<<< END CASE ' or " >>>>>>>>>>>>>>>>>>>>>>>>>> " // <<<<<<<<<<<<<<<<<<< BEGIN CASE $explodedON >>>>>>>>>>>>>>>>>>>>>>> case ($nearest['char'] == $explodeOn): // found a mine (need to explode) // record the stuff up to the end of the mine $explodedStrArr[$numExplosions] = substr( $target, $currentLocale, $nearest['str_loc'] - $currentLocale ); // increment counter $numExplosions++; // change current locale $currentLocale = $nearest['str_loc'] + strlen($explodeOn); break; // <<<<<<<<<<<<<<<<<<<< END CASE $explodedON >>>>>>>>>>>>>>>>>>>>>>>> } // end switch } // end while } ?>

« previous php.notes (#117589) next »