Regular expression for preg_split() by new line

2020-08-20 04:26发布

This is my file:

0.0 5.0 5.0 6.0 7.0 2.0 5.0 2.0 1.0 5.0 5.0 1.0 2.0 7.1 5.0
5.0 0.0 5.0 5.0 5.0 2.0 5.0 1.0 5.0 6.0 6.0 6.0 6.0 1.0 7.1
5.0 5.0 0.0 6.0 1.0 6.0 5.0 5.0 1.0 6.0 5.0 7.0 1.0 5.0 6.0
6.0 5.0 6.0 0.0 5.0 2.0 1.0 6.0 5.0 6.0 2.0 1.0 2.0 1.0 5.0
7.0 5.0 1.0 5.0 0.0 7.0 1.0 1.0 2.0 1.0 5.0 6.0 2.0 2.0 5.0
2.0 2.0 6.0 2.0 7.0 0.0 5.0 5.0 6.0 5.0 2.0 5.0 1.0 2.0 5.0
5.0 5.0 5.0 1.0 1.0 5.0 0.0 2.0 6.0 1.0 5.0 7.0 5.0 1.0 6.0
7.0 1.0 5.0 1.0 2.0 2.0 1.0 5.0 6.0 5.0 2.0 6.0 7.0 0.0 5.0
5.0 7.0 6.0 5.0 5.0 5.0 6.0 2.0 6.0 2.0 1.0 5.0 6.0 5.0 0.0

I would split it by \n and have returned in one array each row. How can I do the regular expression?

$rows = preg_split('$regular_expression', $content);

After I will extract all the rows, how can I extract each value separated by backspace?

$values_in_a_row = preg_split('$regular_expression', $a_row);

Here the text were I am trying to do it http://regexr.com?2v23c .

4条回答
家丑人穷心不美
2楼-- · 2020-08-20 04:34

No need for REGEX, use explode() instead:

<?php

    $file = <<<EOF
    0.0 5.0 5.0 6.0 7.0 2.0 5.0 2.0 1.0 5.0 5.0 1.0 2.0 7.1 5.0
    5.0 0.0 5.0 5.0 5.0 2.0 5.0 1.0 5.0 6.0 6.0 6.0 6.0 1.0 7.1
    5.0 5.0 0.0 6.0 1.0 6.0 5.0 5.0 1.0 6.0 5.0 7.0 1.0 5.0 6.0
    6.0 5.0 6.0 0.0 5.0 2.0 1.0 6.0 5.0 6.0 2.0 1.0 2.0 1.0 5.0
    7.0 5.0 1.0 5.0 0.0 7.0 1.0 1.0 2.0 1.0 5.0 6.0 2.0 2.0 5.0
    2.0 2.0 6.0 2.0 7.0 0.0 5.0 5.0 6.0 5.0 2.0 5.0 1.0 2.0 5.0
    5.0 5.0 5.0 1.0 1.0 5.0 0.0 2.0 6.0 1.0 5.0 7.0 5.0 1.0 6.0
    7.0 1.0 5.0 1.0 2.0 2.0 1.0 5.0 6.0 5.0 2.0 6.0 7.0 0.0 5.0
    5.0 7.0 6.0 5.0 5.0 5.0 6.0 2.0 6.0 2.0 1.0 5.0 6.0 5.0 0.0
    EOF;

    $rows = explode("\n", $file);
    print_r($rows);
    echo "\n\n"; //Spacing

    $numbers_in_a_row = explode(" ", $rows[0]);
    print_r($numbers_in_a_row);

?>

Live Example

查看更多
forever°为你锁心
3楼-- · 2020-08-20 04:44

If you are having issues because you don't know if each newline is just \n or \r\n or \r then none of the above answers work and a regexp works. What I did was

$lines = preg_split("/(\r\n|\n|\r)/",$content);

Then you can use the accepted answer to split the spaces.

查看更多
该账号已被封号
4楼-- · 2020-08-20 04:48
$rowsapart = preg_split("/\n/",$rowstogether);

$colspart = preg_split("/\s/",$colstogether);
查看更多
混吃等死
5楼-- · 2020-08-20 04:59

There isn't any need for regular expressions:

<?php
    $data = explode("\n", $data); // preg_split('#\n#', $data); Please don't
    foreach($data as &$row) {
        $row = explode(' ', $row); // preg_split('#\s#', $row); Seriously
    }
    print_r($data);
?>

<test></test>
查看更多
登录 后发表回答