-->

Regular expression for preg_split() by new line

2020-08-20 04:45发布

问题:

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 .

回答1:

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>


回答2:

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.



回答3:

$rowsapart = preg_split("/\n/",$rowstogether);

$colspart = preg_split("/\s/",$colstogether);


回答4:

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