note 94024 modified in function.explode by danbrown
| From: | danbrown@php.net | Date: | Tue, 13 Oct 2009 15:43:36 +0000 |
| Subject: | note 94024 modified in function.explode by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-161692@lists.php.net to get a copy of this message | ||
Here is a very concise example for a quote aware explode - substrings in quotes (or another
definable enclosure char) are not exploded.
An additional parameter allows to determine whether the enclosure chars should be preserved within
the resulting array elements. Please note that as of PHP 5.3 the str_getcsv function offers a
built-in way to do this!
<?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 example for a quote aware explode - substrings in quotes (or another
definable enclosure char) are not exploded.
An additional parameter allows to determine whether the enclosure chars should be preserved within
the resulting array elements. Please note that as of PHP 5.3 the str_getcsv function offers a
built-in way to do this!
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.explode.php