Just because of the challenge and the pleasure of programming I'm trying to recreate the explode() function in PHP. This is what I have so far:
function explode_by_me($divideBy, $str) {
$element = "";
$elements = array();
for($i=0, $strCount = strlen($str); $i<$strCount; $i++) {
if($str[$i] == $divideBy) {
$elements[] = $element;
$element = "";
}
else {
$element .= $str[$i];
}
}
// add last item
$elements[] = $element;
return $elements;
}
$str = "yo, yo, yo, sexy mama, brhh";
$divideBy = ",";
$explodeNative = explode($divideBy, $str);
$explodeMe = explode_by_me($divideBy, $str);
print_r($explodeNative); //Array ( [0] => yo [1] => yo [2] => yo [3] => sexy mama [4] => brhh )
print_r($explodeMe); //Array ( [0] => yo [1] => yo [2] => yo [3] => sexy mama [4] => brhh )
Everything seems to be fine, except if our $divideBy has more than one char, eg:
$divideBy = ", ";
$explodeNative = explode($divideBy, $str);
$explodeMe = explode_by_me($divideBy, $str);
print_r($explodeNative); //Array ( [0] => yo [1] => yo [2] => yo [3] => sexy mama [4] => brhh )
print_r($explodeMe); //Array ( [0] => yo, yo, yo, sexy mama, brhh )
I realize why this happens, in this case, because we are comparing a single char ( $str[$i] ) to a set of chars (","). Teitei bypass this by changing the condition within our cycle:
if (strpos($divideBy, $str[$i]) !== False) {
$elements[] = $element;
$element = "";
}
But that also does not work:
print_r($explodeNative); //Array ( [0] => yo [1] => yo [2] => yo [3] => sexy mama [4] => brhh )
print_r($explodeMe); //Array ( [0] => yo [1] => [2] => yo [3] => [4] => yo [5] => [6] => sexy [7] => mama [8] => [9] => brhh ) 1
I also realize that this happens because we are creating a new element in the array for every char of $divideBy .
Someone with a solution, to recreate explode() in PHP?





