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
)
This question is related to
php
string
line-breaks
PHP already knows the current system's newline character(s). Just use the EOL constant.
explode(PHP_EOL,$string)
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
<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>
you can use this:
\str_getcsv($str,PHP_EOL);
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.
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);
I've always used this with great success:
$array = preg_split("/\r\n|\n|\r/", $string);
(updated with the final \r, thanks @LobsterMan)
That's my way:
$lines = preg_split('/[\r\n]+/', $db_text, NULL, PREG_SPLIT_NO_EMPTY);
This also will skip all empty lines too.
explode("\n", $str);
The " (instead of ') is quite important as otherwise, the line break wouln't get interpreted.
David: Great direction, but you missed \r. this worked for me:
$array = preg_split("/(\r\n|\n|\r)/", $string);
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.
Picked this up in the php docs:
<?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);
?>
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!
This method always works for me:
$uniquepattern="gd$#%@&~#"//Any set of characters which you dont expect to be present in user input $_POST['text'] better use atleast 32 charecters.
$textarray=explode($uniquepattern,str_replace("\r","",str_replace("\n",$uniquepattern,$_POST['text'])));
$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(); // inisiasi variable array in format array
foreach ($arr as $line) { // loop line by line and convert into array
$array[] = $line;
};
print_r($array); // display all value
echo $array[1]; // diplay index 1
Embed Online:
body, html, iframe { _x000D_
width: 100% ;_x000D_
height: 100% ;_x000D_
overflow: hidden ;_x000D_
}
_x000D_
<iframe src="https://ideone.com/vE1gst" ></iframe>
_x000D_
You don't need preg_* functions nor preg patterns nor str_replace within, etc .. in order to sucessfuly break a string into array by newlines. In all scenarios, be it Linux/Mac or m$, 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.
StackOverflow will not allow me to comment on hesselbom's answer (not enough reputation), so I'm adding my own...
$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);
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)
Source: Stackoverflow.com