How can I put strings in an array, split by new line?
PhpStringLine BreaksPhp Problem Overview
I have a string with line breaks in my database. I want to convert that string into an array, and for every new line, jump one index place in the array.
If the string is:
My text1
My text2
My text3
The result I want is this:
Array
(
[0] => My text1
[1] => My text2
[2] => My text3
)
Php Solutions
Solution 1 - Php
I've always used this with great success:
$array = preg_split("/\r\n|\n|\r/", $string);
(updated with the final \r, thanks @LobsterMan)
Solution 2 - Php
You can use the explode
function, using "\n
" as separator:
$your_array = explode("\n", $your_string_from_db);
For instance, if you have this piece of code:
$str = "My text1\nMy text2\nMy text3";
$arr = explode("\n", $str);
var_dump($arr);
You'd get this output:
array
0 => string 'My text1' (length=8)
1 => string 'My text2' (length=8)
2 => string 'My text3' (length=8)
Note that you have to use a double-quoted string, so \n
is actually interpreted as a line-break.
(See that manual page for more details.)
Solution 3 - Php
A line break is defined differently on different platforms, \r\n, \r or \n.
Using RegExp to split the string you can match all three with \R
So for your problem:
$array = preg_split ('/$\R?^/m', $string);
That would match line breaks on Windows, Mac and Linux!
Solution 4 - Php
PHP already knows the current system's newline character(s). Just use the EOL constant.
explode(PHP_EOL,$string)
Solution 5 - Php
An alternative to Davids answer which is faster (way faster) is to use str_replace
and explode
.
$arrayOfLines = explode("\n",
str_replace(["\r\n","\n\r","\r"],"\n",$str)
);
What's happening is:
Since line breaks can come in different forms, I str_replace
\r\n, \n\r, and \r with \n instead (and original \n are preserved).
Then explode on \n
and you have all the lines in an array.
I did a benchmark on the src of this page and split the lines 1000 times in a for loop and:
preg_replace
took an avg of 11 seconds
str_replace & explode
took an avg of about 1 second
More detail and bencmark info on my forum
Solution 6 - Php
David has a great direction, but it missed \r. This worked for me:
$array = preg_split("/(\r\n|\n|\r)/", $string);
Solution 7 - Php
You don't need preg_* functions, preg patterns, str_replace within, etc. in order to successfully break a string into array by newlines. In all scenarios, be it Linux, Mac, or Windows, this will do.
<?php
$array = explode(PHP_EOL, $string);
// ...
$string = implode(PHP_EOL, $array);
?>
PHP_EOL is a constant holding the line break character(s) used by the server platform.
Solution 8 - Php
Use: $array = preg_split('/\s*\R\s*/', trim($text), NULL, PREG_SPLIT_NO_EMPTY);
This worked best for me because it also eliminates leading (second \s*) and trailing (first \s*) whitespace automatically and also skips blank lines (the PREG_SPLIT_NO_EMPTY flag).
Options
If you want to keep leading whitespace, simply get rid of the second \s* and make it an rtrim() instead...
$array = preg_split('/\s*\R/', rtrim($text), NULL, PREG_SPLIT_NO_EMPTY);
If you need to keep empty lines, get rid of the NULL (it is only a placeholder) and PREG_SPLIT_NO_EMPTY flag, like so...
$array = preg_split('/\s*\R\s*/', trim($text));
Or keeping both leading whitespace and empty lines...
$array = preg_split('/\s*\R/', rtrim($text));
I don't see any reason why you'd ever want to keep trailing whitespace, so I suggest leaving the first \s* in there. But, if all you want is to split by new line (as the title suggests), it is this simple (as mentioned by Jan Goyvaerts)...
$array = preg_split('/\R/', $text);
Solution 9 - Php
explode("\n", $str);
The " (instead of ') is quite important as otherwise, the line break wouln't get interpreted.
Solution 10 - Php
There is quite a mix of direct and indirect answers on this page and some good advice in comments, but there isn't an answer that represents what I would write in my own project.
PHP Escape Sequence \R
documentation: https://www.php.net/manual/en/regexp.reference.escape.php#:~:text=line%20break,\r\n
Code: (Demo)
$string = '
My text1
My text2
My text3
';
var_export(
preg_split('/\R+/', $string, 0, PREG_SPLIT_NO_EMPTY)
);
Output:
array (
0 => 'My text1',
1 => 'My text2',
2 => 'My text3',
)
The OP makes no mention of trimming horizontal whitespace characters from the lines, so there is no expectation of removing \s
or \h
while exploding on variable (system agnostic) new lines.
While PHP_EOL
is sensible advice, it lacks the flexibility appropriately explode the string when the newline sequence is coming from another operating system.
Using a non-regex explode will tend to be less direct because it will require string preparations. Furthermore, there may be mopping up after the the explosions if there are unwanted blank lines to remove.
Using \R+
(one or more consecutive newline sequences) and the PREG_SPLIT_NO_EMPTY
function flag will deliver a gap-less, indexed array in a single, concise function call. Some people have a bias against regular expressions, but this is a perfect case for why regex should be used. If performance is a concern for valid reasons (e.g. you are processing hundreds of thousands of points of data), then go ahead and invest in benchmarking and micro-optimization. Beyond that, just use this one-line of code so that your code is brief, robust, and direct.
Solution 11 - Php
<anti-answer>
As other answers have specified, be sure to use explode
rather than split
because as of PHP 5.3.0 split
is deprecated. i.e. the following is NOT the way you want to do it:
$your_array = split(chr(10), $your_string);
LF = "\n" = chr(10), CR = "\r" = chr(13)
</anti-answer>
Solution 12 - Php
For anyone trying to display cronjobs in a crontab and getting frustrated on how to separate each line, use explode:
$output = shell_exec('crontab -l');
$cron_array = explode(chr(10),$output);
using '\n' doesnt seem to work but chr(10) works nicely :D
hope this saves some one some headaches.
Solution 13 - Php
You can use this:
\str_getcsv($str, PHP_EOL);
Solution 14 - Php
That's my way:
$lines = preg_split('/[\r\n]+/', $db_text, NULL, PREG_SPLIT_NO_EMPTY);
This also will skip all empty lines too.
Solution 15 - Php
You can do a $string = nl2br($string) so that your line break is changed to
<br />.
This way it does not matter if the system uses \r\n or \n or \r
Then you can feed it into an array:
$array = explode("<br />", $string);
Solution 16 - Php
Use:
$str = "My text1\nMy text2\nMy text3";
$arr = explode("\n", $str);
foreach ($arr as $line_num => $line) {
echo "Line #<b>{$line_num}</b>: " . htmlspecialchars($line) . "<br />\n";
}
True array:
$str = "My text1\nMy text2\nMy text3";
$arr = explode("\n", $str);
$array = array();
foreach ($arr as $line) { // loop line by line and convert into array
$array[] = $line;
};
print_r($array); // display all value
echo $array[1]; // display index 1
Embed online:
body, html, iframe {
width: 100%;
height: 100%;
overflow: hidden;
}
<iframe src="https://ideone.com/vE1gst" ></iframe>
Solution 17 - Php
Using only the 'base' package is also a solution for simple cases:
> s <- "a\nb\rc\r\nd"
> l <- strsplit(s,"\r\n|\n|\r")
> l # the whole list...
[[1]]
[1] "a" "b" "c" "d"
> l[[1]][1] # ... or individual elements
[1] "a"
> l[[1]][2]
[1] "b"
> fun <- function(x) c('Line content:', x) # handle as you wish
> lapply(unlist(l), fun)
Solution 18 - Php
I picked this up in the PHP documentation:
<?php
// Split the phrase by any number of commas or space characters,
// which include " ", \r, \t, \n and \f
$keywords = preg_split("/[\s,]+/", "hypertext language, programming");
print_r($keywords);
?>
Solution 19 - Php
This method always works for me:
$uniquepattern = "gd$#%@&~#" // Any set of characters which you don’t expect to be present in user input $_POST['text']. Better use at least 32 characters.
$textarray = explode($uniquepattern, str_replace("\r", "", str_replace("\n", $uniquepattern, $_POST['text'])));