-3

I have string

$string = "one
two
three
four";

Q: How to divide string by "\n" character to array as :

array ('one', 'two', 'three', 'four');
Ranjith
  • 2,779
  • 3
  • 22
  • 41
Ing. Michal Hudak
  • 5,338
  • 11
  • 60
  • 91

5 Answers5

4

Just use the explode function and use the newline character:

$array=explode("\n",$string);

print_r($array);

Having said that, different OS will use different new line breaks. Some will use \n while others will use \r\n which you might want to look into.

You can combine what you are doing with the nl2br function which covers all the options if you really want to - though I would consider it potentially overkill/complicating the issue:

$array=explode("<br>",nl2br($string,false));
print_r($array);
Fluffeh
  • 33,228
  • 16
  • 67
  • 80
2

you can use the PHP_EOL constant which make sure to choose good delimiter :

$array=explode(PHP_EOL,$string);
erwan
  • 48
  • 4
0

Try exploding your string into array

$result = explode("\n", $string);
Bartek
  • 1,349
  • 7
  • 13
0

I think you're after the explode function?

$cake = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $cake);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
l0gic
  • 121
  • 5
0
        $string = "one
        two
        three
        four";

    $arr=explode("\n",$string);
    foreach($arr as $row){
     echo $row.",";
    }
SagarPPanchal
  • 9,839
  • 6
  • 34
  • 62