10

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 .

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
michele
  • 24,748
  • 27
  • 92
  • 146

4 Answers4

40

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.

Bryan
  • 3,071
  • 1
  • 17
  • 22
7

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>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Tom
  • 1,581
  • 10
  • 24
6
$rowsapart = preg_split("/\n/",$rowstogether);

$colspart = preg_split("/\s/",$colstogether);
Michael Krelin - hacker
  • 122,635
  • 21
  • 184
  • 169
2

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

Madara's Ghost
  • 158,961
  • 49
  • 244
  • 292