note 94022 modified in function.str-getcsv by danbrown

From: Date: Wed, 14 Oct 2009 04:14:01 +0000
Subject: note 94022 modified in function.str-getcsv by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-161717@lists.php.net to get a copy of this message
Here is a very concise replacement for str_getcsv. No escaping of the enclosure char though, but an additional possibility to preserve the enclosing characters around a field. Note that the fourth parameter therefore has a different meaning! <?php function csv_explode($delim=',', $str, $enclose='"', $preserve=false){ $resArr = array(); $n = 0; $expEncArr = explode($enclose, $str); foreach($expEncArr as $EncItem){ if($n++%2){ array_push($resArr, array_pop($resArr) . ($preserve?$enclose:'') . $EncItem.($preserve?$enclose:'')); }else{ $expDelArr = explode($delim, $EncItem); array_push($resArr, array_pop($resArr) . array_shift($expDelArr)); $resArr = array_merge($resArr, $expDelArr); } } return $resArr; } ?> --was-- Here is a very concise replacement for str_getcsv. No escaping of the enclosure char though, but an additional possibility to preserve the enclosing characters around a field. Note that the fourth parameter therefore has a different meaning! function csv_explode($delim=',', $str, $enclose='"', $preserve=false){ $resArr = array(); $n = 0; $expEncArr = explode($enclose, $str); foreach($expEncArr as $EncItem){ if($n++%2){ array_push($resArr, array_pop($resArr) . ($preserve?$enclose:'') . $EncItem.($preserve?$enclose:'')); }else{ $expDelArr = explode($delim, $EncItem); array_push($resArr, array_pop($resArr) . array_shift($expDelArr)); $resArr = array_merge($resArr, $expDelArr); } } return $resArr; } http://php.net/manual/en/function.str-getcsv.php

« previous php.notes (#161717) next »