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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:39:40  来源:igfitidea点击:

Explode a string by \r\n & \n & \r at once?

phpunicode

提问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_splitinstead:

您可以使用正则表达式,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 \Rmatches all line breaks of any sort.

在 PHP preg_split()、preg_match 和 preg_replace 中,\R匹配任何类型的所有换行符。

http://www.pcre.org/pcre.txt

http://www.pcre.org/pcre.txt

By default, the sequence \Rin 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 \Rmatches only CR, LF, or CRLF. What- ever is selected when PCRE is built can be overridden when the library functions are called.

默认情况下,\R模式中的序列匹配任何 Unicode 换行序列,无论被选为行尾序列。如果您指定

--enable-bsr-anycrlf

默认的改变,从而\R只匹配CRLFCRLF。构建 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);