正则表达式 - 使用 php 隔离字符串部分


Regex - isolate sections of strings with php

我有一串数据:数字,空格,然后是一个可以包含字母,数字和特殊字符以及空格的单词。我只需要隔离第一个数字,然后只需要隔离单词,以便我可以将数据重新呈现到表中。

1 foo
2   ba_r
3  foo bar
4   fo-o

编辑:我正在尝试使用"^[0-9]+["]",但这不起作用。

您可以使用

此正则表达式来捕获每一行:

/^('d+)'s+(.*)$/m

此正则表达式从每行开始,捕获一个或多个数字,然后匹配一个或多个空格字符,然后捕获任何内容,直到行尾。

然后,使用 preg_match_all() ,您可以获取所需的数据:

preg_match_all( '/^('d+)'s+(.*)$/m', $input, $matches, PREG_SET_ORDER);

然后,你可以从$matches数组中解析出数据,如下所示:

$data = array();
foreach( $matches as $match) {
    list( , $num, $word) = $match;
    $data[] = array( $num, $word);
    // Or: $data[$num] = $word;
}

print_r( $data);将打印:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => foo
        )
    [1] => Array
        (
            [0] => 2
            [1] => ba_r
        )
    [2] => Array
        (
            [0] => 3
            [1] => foo bar
        )
    [3] => Array
        (
            [0] => 4
            [1] => fo-o
        )
)
$str = <<<body
1 foo
2   ba_r
3  foo bar
4   fo-o
body;
preg_match_all('/(?P<numbers>'d+) +(?P<words>.+)/', $str, $matches);
print_r(array_combine($matches['numbers'],$matches['words']));

输出

Array
(
    [1] => foo
    [2] => ba_r
    [3] => foo bar
    [4] => fo-o
)