4
Just for the challenge and the taste of programming I’m trying to recreate the function explode()
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 ours $divideBy
has more than one char, ex:
$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 understand why this happens, in this case, is why we are comparing a single char ($str[$i]
) to a set of chars (", "). I tried to circumvent this by changing the condition within our cycle:
if (strpos($divideBy, $str[$i]) !== False) {
$elements[] = $element;
$element = "";
}
But it doesn’t work either:
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 understand that this happens, as we are creating a new element in the array for each char of $divideBy
.
Someone with a solution, to recreate the explode()
in PHP?
The function explodes from PHP in Javascript to give you an idea: http://phpjs.org/functions/explode/
– Daniel Omine