首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用Regex将列分隔为2个或更多的空格?

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

Stack Overflow用户
提问于 2014-02-03 16:49:09
回答 1查看 77关注 0票数 2

如何获得按Regex分组的列?

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

代码语言:javascript
复制
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

我想对每一行进行迭代,并获得如下的值数组:

代码语言:javascript
复制
$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")
);

我已经编写了regex,选择了一行.*[ ]{2,}.*[ ]{2,}.*$,但是如何将其拆分成列呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-03 16:52:55

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

代码语言:javascript
复制
$arr = preg_split('/ {2,}/', $str);

对于每个输入记录。

代码:

代码语言:javascript
复制
$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);

产出:

代码语言:javascript
复制
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
        )

)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21532911

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档