智能爆炸或其他东西

时间:2017-09-11 09:47:32

标签: php

我有阵列:

$array = [
    'aaa 3',
    'bbb 15',
    'ccccc 3A',
    'dddd 2412',
    'eee fff 15',
    'ggg 612',
    'hhh iiiii 23B',
];

我想收到:

$name = 'aaa'; $number = '3';
$name = 'bbb'; $number = '15';
$name = 'ccccc'; $number = '3A';
$name = 'dddd'; $number = '2412';
$name = 'eee'; $number = '15';
$name = 'ggg'; $number = '612';
$name = 'hhh iiiii'; $number = '23B';

所以我这样做:

foreach ($array as $item) {
    $expl = explode(' ', $item);
    $name = $expl[0];
    $number = $expl[1];
}

但这不适用于eee fff 15hhh iiiii 23B,因为这些名称有两个部分。怎么更好的方法呢?

4 个答案:

答案 0 :(得分:2)

使用正则表达式:

<?php

$array = [
    'aaa 3',
    'bbb 15',
    'ccccc 3A',
    'dddd 2412',
    'eee fff 15',
    'ggg 612',
    'hhh iiiii 23B',
];

$regex = '#(?<word>.+)\s(?<number>.+)#';
$results = [];

foreach ($array as $line) {
    preg_match($regex, $line, $matches);
    $results[$matches['word']] = $matches['number'];
}

var_dump($results);

2个捕获组,首先是任何字符.+,然后是空格\s,然后是任何字符.+

输出:

array(7) { ["aaa"]=> string(1) "3" ["bbb"]=> string(2) "15" ["ccccc"]=> string(2) "3A" ["dddd"]=> string(4) "2412" ["eee fff"]=> string(2) "15" ["ggg"]=> string(3) "612" ["hhh iiiii"]=> string(3) "23B" }

在此处查看:https://3v4l.org/t2tMd

答案 1 :(得分:1)

你需要查看数组的大小,只选择最后一个数字,其余的名称......

foreach ($array as $item) {
    $expl = explode(' ', $item);
    $name = implode(" ", array_slice($expl,0,-1));
    $number = $expl[count($expl)-1];

    echo $name."=". $number.PHP_EOL;
}

答案 2 :(得分:0)

试试这个,

foreach ($array as $item) {
    $expl = explode(' ', $item);
    $division=array_pop($expl);
    $name = $expl[0].' '.$expl[1];
    $number = $division;
}

答案 3 :(得分:0)

有点迟到了,但我想提出我的建议如何做到这一点。 如果您想要的$number始终位于数组的末尾,则$name的大小无关紧要

$newArray = array();
foreach ($array as $item) {
    $expl = explode(' ', $item);
    //get the size of the array
    $last= count($expl)-1;

    //get the final element in the array
    $number = $expl[$last];

    //remove the last element from array
    unset($expl[$last]);

    //glue it back together
    $name = implode(" ",$expl);

    //set the name + number in our array
    $newArray[]=array('name' => $name,'number'=>$number);

}


print_r($newArray);

//Output:
/* Array ( 
        [0] => Array ( 
            [name] => aaa 
            [number] => 3 
        )
        [1] => Array ( 
            [name] => bbb 
            [number] => 15 
        ) 
        [2] => Array ( 
            [name] => ccccc 
            [number] => 3A 
        ) 
        [3] => Array (
            [name] => dddd 
            [number] => 2412 
        ) 
        [4] => Array ( 
            [name] => eee fff 
            [number] => 15 
        ) 
        [5] => Array ( 
            [name] => ggg 
            [number] => 612 
        ) 
        [6] => Array ( 
            [name] => hhh iiiii 
            [number] => 23B 
        )       
    ) 
*/