Question

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
)
Was it helpful?

Solution

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)

OTHER TIPS

I've always used this with great success:

$array = preg_split("/\r\n|\n|\r/", $string);

(updated with the final \r, thanks @LobsterMan)

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!

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(array("\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

David: Great direction, but you missed \r. this worked for me:

$array = preg_split("/(\r\n|\n|\r)/", $string);
explode("\n", $str);

The " (instead of ') is quite important as otherwise, the line break wouln't get interpreted.

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);
<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>

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.

you can use this:

 \str_getcsv($str,PHP_EOL);

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);
$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 { 
  width: 100% ;
  height: 100% ;
  overflow: hidden ;
}
<iframe src="https://ideone.com/vE1gst" ></iframe>

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);
?>

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'])));

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)

That's my way:

$lines = preg_split('/[\r\n]+/', $db_text, NULL, PREG_SPLIT_NO_EMPTY);

This also will skip all empty lines too.

Using any special character between the string or line break \n using PHP explode we can achieve this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top