note 33041 modified in function.explode by aidan
| From: | aidan@php.net | Date: | Sun, 27 Jun 2004 14:14:46 +0000 |
| Subject: | note 33041 modified in function.explode by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-71913@lists.php.net to get a copy of this message | ||
A note to the CVS Explode Function posted. (cvs_explode2)
The function posted doesn't care about quotes inside quotes.. Example:
"string1";"string2"
will result in
[0] = "string1"
[1] = "string2"
But.. Excel XP encodes quotes using double quotes.. so..
"string1""","""string2"
in Excel this is:
string1"
"string2
the posted function will continue returning:
[0] = "string1"
[1] = "string2"
I modified the function:
<?php
// Separa una lína de CSV en una matriz
function csv_separa ($str, $delim=';', $qual="\"")
{
// Largo de la línea
$largo=strlen($str);
// Dentro
$dentro=false;
// Palabra
$palabra="";
// Bucle
for ( $i=0; $i<$largo; $i++)
{
if ( $str[$i] == $delim && !$dentro )
{
$salida[] = $palabra;
$palabra="";
}
else if ( $str[$i] == $qual && ( $i<$largo && $str[$i+1] == $qual
) )
{
$palabra .= $qual;
$i++;
}
else if ( $str[$i] == $qual )
{
$dentro = !$dentro;
}
else
{
$palabra .= $str[$i];
}
}
// Devolvemos la matriz
$salida[]=$palabra;
return $salida;
}
?>
And now.. the same example returns:
[0] = "string1\""
[1] = "\"string2"
The function asumes that double $qual means a single $qual in the final string to be returned.
This is my first post.. I hope it's helpful..
Greetings from Concepción, Chile!
--was--
A note to the CVS Explode Function posted. (cvs_explode2)
The function posted doesn't care about quotes inside quotes.. Example:
"string1";"string2"
will result in
[0] = "string1"
[1] = "string2"
But.. Excel XP encodes quotes using double quotes.. so..
"string1""","""string2"
in Excel this is:
string1"
"string2
the posted function will continue returning:
[0] = "string1"
[1] = "string2"
I modified the function:
// Separa una lína de CSV en una matriz
function csv_separa ($str, $delim=';', $qual="\"")
{
// Largo de la línea
$largo=strlen($str);
// Dentro
$dentro=false;
// Palabra
$palabra="";
// Bucle
for ( $i=0; $i<$largo; $i++)
{
if ( $str[$i] == $delim && !$dentro )
{
$salida[] = $palabra;
$palabra="";
}
else if ( $str[$i] == $qual && ( $i<$largo && $str[$i+1] == $qual
) )
{
$palabra .= $qual;
$i++;
}
else if ( $str[$i] == $qual )
{
$dentro = !$dentro;
}
else
{
$palabra .= $str[$i];
}
}
// Devolvemos la matriz
$salida[]=$palabra;
return $salida;
}
And now.. the same example returns:
[0] = "string1\""
[1] = "\"string2"
The function asumes that double $qual means a single $qual in the final string to be returned.
This is my first post.. I hope it's helpful..
Greetings from Concepción, Chile!
http://php.net/manual/en/function.explode.php