note 61925 deleted from function.explode by bjori
| From: | bjori@php.net | Date: | Mon, 25 Sep 2006 08:06:30 +0000 |
| Subject: | note 61925 deleted from function.explode by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-117569@lists.php.net to get a copy of this message | ||
Note Submitter: markus dot schabel at tgm dot ac dot at
----
My version looks like the following:
<?php
/**
* Explode a string by delimiters, but ignore delimiters inside encapsulation.
*
* This function works like the explode() function, but takes care that
* delimiters inside encapsulated parts are ignored. This is useful for CSV
* files, where the parts may be encapsulated by " or ', and any delimiter
* between two encapsulation characters is part of the string, so this part
* cannot be exploded.
* Note however, when reading data from a CSV file, the PHP function fgetcsv()
* should be used.
*
* @param string $delim is the delimiter that should be used for splitting.
* @param string $string is the string that should be splitted.
* @param string $encap is the encapsulation character.
*
* @return array of string that contains the splitted parts.
*/
function quote_explode( $delim, $string, $encap = '"' ) {
$parts = explode( $delim, $string );
$correctParts = array();
$correctIndex = 0;
$insideEncaps = false;
foreach ( $parts as $part ) {
$numEncaps = substr_count( $part, $encap );
if ( !$insideEncaps ) {
switch ( $numEncaps ) {
case 1:
$correctParts[$correctIndex] = str_replace( $encap,
'', $part );
$insideEncaps = true;
break;
case 0:
case 2:
$correctParts[$correctIndex++] = str_replace( $encap,
'', $part );
break;
default:
echo 'Found more than 2 encapsulations - this should
not happen!';
}
} else {
switch ( $numEncaps ) {
case 0:
$correctParts[$correctIndex] .= ';'.str_replace(
$encap, '', $part );
break;
case 1:
$correctParts[$correctIndex++] .= ';'.str_replace(
$encap, '', $part );
$insideEncaps = false;
break;
default:
echo 'Found more than 2 encapsulations - this should
not happen!';
}
}
}
return $correctParts;
}
?>
However, I just replaced it with fgetcsv(). There really should be a see-also link to the fgetcsv()
function. ;-))