如何使用Regex将列分隔2个或更多空格?

时间:2014-02-03 16:49:10

标签: php regex

如何获取按Regex分组的列?

我在“列”中有数据(列由两个或多个空格分隔):

ii  acpi                                1.5-2                        displays information on ACPI devices
ii  acpi-support-base                   0.137-5                      scripts for handling base ACPI events such as the power button
ii  acpid                               1:2.0.7-1squeeze4            Advanced Configuration and Power Interface event daemon

我想迭代每一行并得到如下数组的值:

$outputWouldBe = array(
    array("ii", "acpi", "1.5-2", "displays information on ACPI devices"),
    array("ii", "acpi-support-base", "0.137-5", "scripts for handling base ACPI events such as the power button"),
    array("ii", "acpid", "1:2.0.7-1squeeze4", "Advanced Configuration and Power Interface event daemon")
);

我写过正则表达式选择一行.*[ ]{2,}.*[ ]{2,}.*$,但是如何按列拆分?

1 个答案:

答案 0 :(得分:1)

我相信你可以像这样分开:

$arr = preg_split('/ {2,}/', $str);
每个输入记录

代码:

$s = <<< EOF
ii  acpi                                1.5-2                        displays information on ACPI devices
ii  acpi-support-base                   0.137-5                      scripts for handling base ACPI events such as the power button
ii  acpid                               1:2.0.7-1squeeze4            Advanced Configuration and Power Interface event daemon
EOF;
$outputWouldBe = array();
$lines = explode("\n", $s);
foreach($lines as $line) {
   #echo "$line => ";
   $m = preg_split('/(?: {2,}|\n)/', $line);
   $outputWouldBe[] = $m;
}
print_r($outputWouldBe);

输出:

Array
(
    [0] => Array
        (
            [0] => ii
            [1] => acpi
            [2] => 1.5-2
            [3] => displays information on ACPI devices
        )

    [1] => Array
        (
            [0] => ii
            [1] => acpi-support-base
            [2] => 0.137-5
            [3] => scripts for handling base ACPI events such as the power button
        )

    [2] => Array
        (
            [0] => ii
            [1] => acpid
            [2] => 1:2.0.7-1squeeze4
            [3] => Advanced Configuration and Power Interface event daemon
        )

)