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行,根据定义,它是最后一行.)
必须遵循以下规则:
所以这应该导致以下数组:
[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'和诸如此类的东西,但我找不到符合我上面概述的两条规则的好的正则表达式.有什么帮助吗?
只是用于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)如果有一个尾随换行符,您可能还想要,因此最终不会有一个额外的空数组元素.
| 归档时间: |
|
| 查看次数: |
2462 次 |
| 最近记录: |