How to put string in array, split by new line?

2019-01-01 10:08发布

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
)

18条回答
大哥的爱人
2楼-- · 2019-01-01 10:44

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.

查看更多
与君花间醉酒
3楼-- · 2019-01-01 10:44
$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>

查看更多
其实,你不懂
4楼-- · 2019-01-01 10:45

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

查看更多
查无此人
5楼-- · 2019-01-01 10:46
<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>
查看更多
流年柔荑漫光年
6楼-- · 2019-01-01 10:48

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!

查看更多
栀子花@的思念
7楼-- · 2019-01-01 10:50

PHP already knows the current system's newline character(s). Just use the EOL constant.

explode(PHP_EOL,$string)
查看更多
登录 后发表回答