note 109403 modified in function.explode by googleguy

From: Date: Thu, 22 Nov 2012 16:40:08 +0000
Subject: note 109403 modified in function.explode by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-192082@lists.php.net to get a copy of this message
Explode does not parse a string by delimiters, in the sense that we expect to find tokens between a starting and ending delimiter, but instead splits a string into parts by using a string as the boundary of each part. Once that boundary is discovered the string is split. Whether or not that boundary is proceeded or superseded by any data is irrelevant since the parts are determined at the point a boundary is discovered. For example: <?php var_dump(explode(\"/\",\"/\")); /* Outputs array(2) { [0]=> string(0) \"\" [1]=> string(0) \"\" } */ ?> The reason we have two empty strings here is that a boundary is discovered before any data has been collected from the string. The boundary splits the string into two parts even though those parts are empty. One way to avoid getting back empty parts (if you don\'t care for those empty parts) is to use array_filter on the result. <?php var_dump(array_filter(explode(\"/\",\"/\"))); /* Outputs array(0) { } */ ?> *[This note was edited by googleguy at php dot net for clarity]* --was-- 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); ?> http://php.net/manual/en/function.explode.php

« previous php.notes (#192082) next »