开发者

Explode a string by \r\n & \n & \r at once? [duplicate]

This question already has answers here: Reliably split user-submitted textarea value on newlines (6 answers) 开发者_C百科 Closed 7 months ago.

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

And return an array containing each line.


You can use a regular expression and preg_split instead:

$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.


preg_split('/\R/', $str);

In PHP preg_split(), preg_match, and preg_replace the \R matches all line breaks of any sort.

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

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


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜