php 一次用 \r\n & \n & \r 分解一个字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5053373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Explode a string by \r\n & \n & \r at once?
提问by Ryan
I want to split a string by lines but i want it to be based on all the major used line breaks characters:
我想按行拆分字符串,但我希望它基于所有主要使用的换行符:
- \n
- \r\n
- \r
- \n
- \r\n
- \r
And return an array containing each line.
并返回一个包含每一行的数组。
回答by Gumbo
You can use a regular expression and preg_split
instead:
您可以使用正则表达式,preg_split
而是:
$lines = preg_split('/\n|\r\n?/', $str);
The regular expression \n|\r\n?
matches either a LF or a CR that may be followed by a LF.
正则表达式\n|\r\n?
匹配 LF 或可能后跟 LF 的 CR。
回答by jerrygarciuh
preg_split('/\R/', $str);
preg_split('/\R/', $str);
In PHP preg_split(), preg_match, and preg_replace the \R
matches all line breaks of any sort.
在 PHP preg_split()、preg_match 和 preg_replace 中,\R
匹配任何类型的所有换行符。
By default, the sequence
\R
in a pattern matches any Unicode newline sequence, whatever has been selected as the line ending sequence. If you specify
--enable-bsr-anycrlf
the default is changed so that
\R
matches onlyCR
,LF
, orCRLF
. What- ever is selected when PCRE is built can be overridden when the library functions are called.
默认情况下,
\R
模式中的序列匹配任何 Unicode 换行序列,无论被选为行尾序列。如果您指定
--enable-bsr-anycrlf
默认的改变,从而
\R
只匹配CR
,LF
或CRLF
。构建 PCRE 时选择的任何内容都可以在调用库函数时被覆盖。
回答by lucke84
You can replace all occourences of breaking characters with a unique placeholder and then explode the string in an array, doing something like this:
您可以使用唯一的占位符替换所有出现的中断字符,然后将字符串分解为数组,执行如下操作:
$my_string = preg_replace(array('/\n/', '/\r/'), '#PH#', $my_string);
$my_array = explode('#PH', $my_string);