在一个或另一个字符之后分割字符串


Split string after one character or another

我有一个包含许多行的文件,如下所示:

2011-03-23  10:11:08    34  57  2   25,5    -
2011-03-23  10:11:12    67  54  3   3,5 -
2011-03-23  10:11:16    76  57  3   2,4 -
2011-03-23  10:11:18    39  41  2   25,5    +

每一行以+-结尾。我希望文件内容在+-符号之后被分割。行没有相同的字符数

我试图使用fgets()auto_detect_line_endings读取文件,但仍然有许多行合并成一个:

输出示例:输出应该是两行,但只有一行(你可以看到"the new line",但PHP没有):

2011-03-23 10:11:08 34 57 2 25,5 - 2011-03-23 10:11:12 67 54 3 3,5 -

编辑:

我用来读取文件 的代码
ini_set('auto_detect_line_endings', true);
    $handle = fopen($filename, "r");
    $index = 1;
    if ($handle) {
        while (($line = fgets($handle)) !== false) {
            if (trim($line) != '') {
                $data = preg_split('/'s+/', trim($line));
                // Saving into DB...
                $index++;
            }
        }
    }
    fclose($handle);

为了确保您获得所有可能的新行组合,您应该使用preg_split代替:

LF = 'n, CR = 'r

LF:多操作系统、Unix及类Unix系统(GNU/Linux、OS X、FreeBSD、AIX、Xenix等)、BeOS、Amiga、RISC OS等。
CR: Commodore 8位机,Acorn BBC, ZX Spectrum, TRS-80, Apple II系列,Mac OS 9和OS-9
LF+CR: Acorn BBC和RISC OS假脱机文本输出。
CR+LF: Microsoft Windows, DEC TOPS-10, RT-11和大多数其他早期非unix和非ibm操作系统,CP/M, MP/M, DOS (MS-DOS, PC DOS等),Atari TOS, OS/2, Symbian OS, Palm OS, Amstrad CPC

正则表达式为/('r'n|'n'r|'n|'r)/ (CR+LFLF+CRLFCR):

$lines = preg_split('/('r'n|'n'r|'n|'r)/', $string);


如果你计划没有任何空行(行与空白计数为空),你可以添加一个可选的's*到你的regex的末尾,它将匹配0到你的换行符后的无限大的空白:

$lines = preg_split('/('r'n|'n'r|'n|'r)'s*/', $string);


如果您计划不使用任何空行,但希望有空格的行不将计数为空,您甚至可以简化正则表达式:

$lines = preg_split('/['n'r]+/', $string);

TRY THIS:

<?php
  $input = "2011-03-23  10:11:08    34  57  2   25,5    -
          2011-03-23  10:11:12    67  54  3   3,5 -
          2011-03-23  10:11:16    76  57  3   2,4 -
          2011-03-23  10:11:18    39  41  2   25,5    +";
  // 1st explode by new line
  $output = explode("'n", $input);
  print_r($output);

  // 2nd remove last character
  $result = array();
  foreach($output as $op)
  {
     $result[] = substr($op, 0, -1);
  }
  print_r($result);


输出:

Array
(
   [0] => 2011-03-23  10:11:08    34  57  2   25,5    -
   [1] => 2011-03-23  10:11:12    67  54  3   3,5 -
   [2] => 2011-03-23  10:11:16    76  57  3   2,4 -
   [3] => 2011-03-23  10:11:18    39  41  2   25,5    +
)
Array
(
   [0] => 2011-03-23  10:11:08    34  57  2   25,5    
   [1] => 2011-03-23  10:11:12    67  54  3   3,5 
   [2] => 2011-03-23  10:11:16    76  57  3   2,4 
   [3] => 2011-03-23  10:11:18    39  41  2   25,5    
)


演示:
http://3v4l.org/0uIe7 v430