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)
    )
有帮助吗?

解决方案

<?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);

其他提示

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);

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top