how to do explode function in php after every 2nd commas

        question                         jiby, t, joby, p,  


        expected answer                  jiby,t
                                         joby,p

explode is not that intelligent.

any other ways in php to get the answer like that?

Member Avatar
diafol

You can explode on commas, then combine pairs of array items. Alternatively you could use a strpos/substr in a loop and do similar.

ALso this thread post: http://stackoverflow.com/a/5956463/4629068 - I really like this.

Iam new to php would you please show the code to get the result...

Each string behaves as a potential array so calculate string length and traverse the string as an array unless you found desired nth element to separate the string. Log the position of nth element and use "substr" function to extract that particular part of string in some array.

Hope that helps.

Member Avatar
diafol

Iam new to php would you please show the code to get the result..

Did you try the code in the link? Really shouldn't have to copy it here.

I am writing this no as response to the question that smells like a test , I am writing it because I believe that there is a bad perception for php functions as arguments (I hate PHP that way and luckily PHP hate itself as well) . I will give you a test code that I would like you to run in order to understand ... and test your own what is faster and more sufficient , that might change the way you are thinking.

<?php
class _StringUtils
{
    public static function splitEveryNth($string,$delimiter,$n)
    {
            $arr = array();
            $parts = explode($delimiter, $string);
            $i = 0;
            $index = 0;
            while( $i < count($parts) )
            {
                $left = $i % $n;
                if($left == 0)
                {
                    $index++;
                    $arr[$index] = "";
                }
                $arr[$index] .= $parts[$i] .  ($left == $n - 1 ? "" : $delimiter);
                $i++;
            }
            return $arr; 
    }

    public static function split_nth($str, $delim, $n)
    {
        return array_map(function($p) use ($delim) {
            return implode($delim, $p);
        }, array_chunk(explode($delim, $str), $n));
    }
}

echo "Test split_nth";
$string = "jiby, t, joby, p";
$re = "";
$time = microtime(true);
echo "<br/>";
for($i=0; $i<10000; $i++)
{
    $re = _StringUtils::split_nth($string, ",", 2);
}
echo "<br/>";
echo (microtime(true) - $time);
echo "<br/>";
var_dump($re); 
echo "<br/>";
echo "Test splitEvertyNth";
echo "<br/>";
$time = microtime(true);
for($i=0; $i<10000; $i++)
{
    $re = _StringUtils::splitEveryNth($string, ",", 2);
}
echo "<br/>";
echo (microtime(true) - $time);
echo "<br/>";
var_dump($re); 
?>