I want to split a string by lines but i want it to be based on all the major used line breaks characters:
And return an array containing each line.
Split a string at a newline character. When the literal \n represents a newline character, convert it to an actual newline using the compose function. Then use splitlines to split the string at the newline character. Create a string in which two lines of text are separated by \n .
To split a string by newline, call the split() method passing it the following regular expression as parameter - /\r?\ n/ . The split method will split the string on each occurrence of a newline character and return an array containing the substrings.
We used the str. strip() method to remove any leading or trailing spaces from the string before calling the split() method. If you need to split a string only on the first whitespace character, don't provide a value for the separator argument when calling the str. split() method.
Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With