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 onlyCR
,LF
, orCRLF
. 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);
精彩评论