note 109403 modified in function.explode by danbrown
| From: | danbrown@php.net | Date: | Mon, 16 Jul 2012 15:18:50 +0000 |
| Subject: | note 109403 modified in function.explode by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-189176@lists.php.net to get a copy of this message | ||
There is a problem in explode in that it doesn't parse correctly leaving the wrong counts
and tokens on return. For
example: <?php $str =
"/"; $parts = explode("/",
$str); $numParts = count($parts); echo "String: "
. $str . " Count: " . $numParts .
"<br/>"; ?> Will
actually say there are two tokens of empty
strings. <?php $str =
"/a/"; $parts = explode("/",
$str); $numParts = count($parts); echo "String: "
. $str . " Count: " . $numParts .
"<br/>"; ?> Will
say there are three tokens, two empty and one with the 'a' in
it. This is not useful information. All you want are the tokens
separated by the delimiter. To have to go back and iterate through the returned token array again is
an unnecessary step. The solution is to filter each token for the
empty condition: <?php function
explode_filtered_empty($var) { if ($var == "")
return(false); return(true); } function
explode_filtered($delimiter, $str) { $parts = explode($delimiter,
$str); return(array_filter($parts,
"explode_filtered_empty")); } $parts
= explode_filtered("/", $str); $numParts =
count($parts); echo "String: " . $str . " Count: "
. $numParts .
"<br/>"; var_dump($parts); ?>
--was--
There is a problem in explode in that it doesn't parse correctly leaving the wrong counts and
tokens on return. For example:
$str = "/";
$parts = explode("/", $str);
$numParts = count($parts);
echo "String: " . $str . " Count: " . $numParts . "<br/>";
Will actually say there are two tokens of empty strings.
$str = "/a/";
$parts = explode("/", $str);
$numParts = count($parts);
echo "String: " . $str . " Count: " . $numParts . "<br/>";
Will say there are three tokens, two empty and one with the 'a' in it.
This is not useful information. All you want are the tokens separated by the delimiter. To have to
go back and iterate through the returned token array again is an unnecessary step.
The solution is to filter each token for the empty condition:
function explode_filtered_empty($var) {
if ($var == "")
return(false);
return(true);
}
function explode_filtered($delimiter, $str) {
$parts = explode($delimiter, $str);
return(array_filter($parts, "explode_filtered_empty"));
}
$parts = explode_filtered("/", $str);
$numParts = count($parts);
echo "String: " . $str . " Count: " . $numParts . "<br/>";
var_dump($parts);
You can read more about why you want to replace the explode call with explode_filtered here:
http://kobashicomputing.com/fixing-phps-explode-function
http://php.net/manual/en/function.explode.php