0

I have strings of data: number, space(s), then a word that can contain letters, numbers and special characters as well as spaces. I need to isolate the first number only, and then also the words only so I can re-render the data into a table.

1 foo
2   ba_r
3  foo bar
4   fo-o

EDIT: I was attempting this with "^[0-9]+[" "]" however that doesn't work.

4

2 回答 2

3

您可以使用此正则表达式来捕获每一行:

/^(\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;
}

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

)
于 2013-06-12T15:00:44.653 回答
2
$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
)
于 2013-06-12T15:01:28.517 回答