note 109403 added to function.explode
| From: | kkobashi at kobashicomputing dot com | Date: | Sat, 14 Jul 2012 03:36:06 +0000 |
| Subject: | note 109403 added to function.explode | ||
| Groups: | php.notes php.notes | ||
| Request: | Send a blank email to php-notes+get-189133@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:
$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
----
Server IP: 64.71.164.2
Probable Submitter: 204.152.219.48
----
Manual Page -- http://www.php.net/manual/en/function.explode.php
Edit -- https://master.php.net/note/edit/109403
Del: integrated -- https://master.php.net/note/delete/109403/integrated
Del: useless -- https://master.php.net/note/delete/109403/useless
Del: bad code -- https://master.php.net/note/delete/109403/bad+code
Del: spam -- https://master.php.net/note/delete/109403/spam
Del: non-english -- https://master.php.net/note/delete/109403/non-english
Del: in docs -- https://master.php.net/note/delete/109403/in+docs
Del: other reasons-- https://master.php.net/note/delete/109403
Reject -- https://master.php.net/note/reject/109403
Search -- https://master.php.net/manage/user-notes.php