Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

unicode

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.

like image 386
CodeOverload Avatar asked Feb 19 '11 20:02

CodeOverload


People also ask

How do I split a string into a new 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 .

How can I put strings in an array split by New Line?

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.

How do I split a string on one space?

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.

How do you split a string into elements?

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.


2 Answers

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.

like image 188
Gumbo Avatar answered Oct 02 '22 15:10

Gumbo


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.

like image 23
jerrygarciuh Avatar answered Oct 02 '22 16:10

jerrygarciuh