1

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

        question                         jiby, t, joby, p,  


        expected answer                  jiby,t
                                         joby,p
5
Contributors
7
Replies
36
Views
1 Year
Discussion Span
Last Post by jkon
0

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

-1

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

0

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.

1

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.

0

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); 
?>
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.