-2

My input is this:

$str = ' 1. Admin, Administrator,3. Visor, Super,4. Team, Super User,5. lastname, employee'

how can I have the following output using array Explode?

 array(
        [0] => Array ( [0] => 1 [1] => Admin [2] => Administrator)
        [1] => Array ( [0] => 3 [1] => Visor [2] => Super)
        [2] => Array ( [0] => 4 [1] => Team [2] => Super User)
        [3] => Array ( [0] => 5 [1] => lastname [2] => employee)
    )
Daphnne
  • 116
  • 1
  • 1
  • 12
  • implode is not what you desire. how is your output "1. Admin, Administrator,3. Visor, Super,4. Team, Super User,5. lastname, employee" to begin with, needs to be mentioned. – skrilled Dec 10 '13 at 01:43
  • what will be? @skrilled – Daphnne Dec 10 '13 at 01:44
  • how? can you give me an example? – Daphnne Dec 10 '13 at 01:45
  • Like this? Do some homework yourself before you ask your next question. https://eval.in/77783 – scrowler Dec 10 '13 at 01:51
  • If it's possible to have that second comma replaced by a semi colon or a new line char it would be much safer to process this data. I'm aware that might not be possible, but if it is make it happen. – Lenny Dec 10 '13 at 01:52

3 Answers3

6
<?php
$str = '1. Admin, Administrator,3. Visor, Super,4. Team, Super User,5. lastname, employee';
$str = str_replace('.', ',', $str);
$arr = explode(',', $str);
$arr = array_chunk ($arr, 3); 
var_export($arr);
srain
  • 8,944
  • 6
  • 30
  • 42
1

Here is another option... This is not a really safe way to get data, but as long as the input is ALWAYS PERFECTLY in this format this will work. The main difference is this one trims the whitespace.

You could also use the other answer and just do str_replace(' ','' before you start

$myString="1. Admin, Administrator,3. Visor, Super,4. Team, Super User,5. lastname, employee";
$myOutput=array();
$myFirstSplit = explode(",",$myString);
foreach($myFirstSplit  as $myKey=> $myVal){
    $myNextSplit=explode('.',$myVal);
    if(count($myNextSplit) > 1){
        $myOutput[$myKey]=array(trim($myNextSplit[0]),trim($myNextSplit[1]));
    }else{
        $myOutput[$myKey-1][]=trim($myNextSplit[0]);
    }
}
var_dump($myOutput);
Lenny
  • 5,663
  • 2
  • 19
  • 27
1

Another solution which trims the output and is a little bit faster than srain's (nice) solution:

$str = '1. Admin, Administrator,3. Visor, Super,4. Team, Super User,5. lastname, employee';
$tok = strtok($str, ".,");
$output = array();
while ($tok !== false) {
    $output[] = trim($tok);
    $tok = strtok(".,");
}
$output = array_chunk($output, 3);

echo '<pre>';
print_r($output);
bitWorking
  • 12,485
  • 1
  • 32
  • 38