使用PHP中的正则表达式将多行字符串转换为多元素数组

x74*_*x61 2 php regex newline preg-match-all

我需要拆分以下字符串并将每个新行放入一个新的数组元素中.

this is line a.(EOL chars = '\r\n' or '\n')
(EOL chars)
this is line b.(EOL chars)
this is line c.(EOL chars)
this is the last line d.(OPTIONAL EOL chars)
Run Code Online (Sandbox Code Playgroud)

(请注意,最后一行可能没有任何EOL字符.字符串有时也只包含1行,根据定义,它是最后一行.)

必须遵循以下规则:

  • 应丢弃空行(如第二行),不要将其放入数组中.
  • 不应包含EOL字符,否则我的字符串比较会失败.

所以这应该导致以下数组:

[0] => "this is line a."
[1] => "this is line b."
[2] => "this is line c."
[3] => "this is the last line d."
Run Code Online (Sandbox Code Playgroud)

我尝试过以下操作:

$matches = array();
preg_match_all('/^(.*)$/m', $str, $matches);
return $matches[1];
Run Code Online (Sandbox Code Playgroud)

$ matches [1]确实包含每个新行,但是:

  • 还包括空行
  • 似乎一个'\ r'字符无论如何都会在数组中的字符串末尾被走私.我怀疑这与正则表达式范围有关.' 其中包括除'\n'以外的所有内容.

无论如何,我一直在玩'\ R'和诸如此类的东西,但我找不到符合我上面概述的两条规则的好的正则表达式.有什么帮助吗?

Mic*_*ski 5

只是用于preg_split()拆分正则表达式:

// Split on \n, \r is optional..
// The last element won't need an EOL.
$array = preg_split("/\r?\n/", $string);
Run Code Online (Sandbox Code Playgroud)

注意,trim($string)如果有一个尾随换行符,您可能还想要,因此最终不会有一个额外的空数组元素.