如何将字符串放入数组,由新行拆分?

时间:2022-05-29 09:27:30

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

我的text1我的text3。

The result I want is this:

我想要的结果是:

Array
(
    [0] => My text1
    [1] => My text2
    [2] => My text3
)

17 个解决方案

#1


219  

You can use the explode function, using "\n" as separator :

您可以使用“\n”作为分隔符:

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

注意,您必须使用一个双引号字符串,所以\n实际上被解释为一个行中断。(详情请参阅手册页)

#2


249  

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

使用RegExp分割字符串,您可以将所有三个与\R匹配。

So for your problem:

对于你的问题:

$array = preg_split ('/$\R?^/m', $string);

That would match line breaks on Windows, Mac and Linux!

这将会在Windows, Mac和Linux上匹配换行符!

#3


240  

I've always used this with great success:

我一直都非常成功地使用这个方法:

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

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

(用最后的\r更新,谢谢@LobsterMan)

#4


32  

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

PHP已经知道当前系统的换行符。只用EOL常数。

explode(PHP_EOL,$string)

#5


23  

An alternative to Davids answer which is faster (way faster) is to use str_replace and explode.

Davids回答的另一个选择是使用str_replace和爆炸。

$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.

发生的情况是:由于换行符可以以不同的形式出现,所以我将替换\r\n、\n\r和\r和\n(保留原来的\n)。然后爆炸在\n,你有所有的线在一个数组。

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

我在这个页面的src上做了一个基准测试,并在for循环中对行进行了1000次的拆分:preg_replace使用了一个11秒的avg,然后使用了大约1秒的avg。

More detail and bencmark info on my forum

更多细节和bencmark信息在我的论坛。

#6


17  

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

大卫:方向很好,但你错过了。这工作对我来说:

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

#7


9  

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.

您不需要preg_*函数、preg模式或str_replace在内,等等。为了成功地用换行符将字符串分割成数组。在所有的场景中,无论是Linux/Mac还是m$,这都可以。

<?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.

PHP_EOL是服务器平台使用的行中断字符(s)的常量。

#8


8  

explode("\n", $str);

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

“(而不是)很重要,否则,换行不会被解释。”

#9


7  

<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:

正如其他答案所指定的那样,一定要使用爆炸,而不是拆分,因为在PHP 5.3.0分割的时候是不赞成的。以下不是你想要的方式:

$your_array = split(chr(10), $your_string);

LF = "\n" = chr(10), CR = "\r" = chr(13)

LF = "\n" = chr(10), CR = "\r" = chr(13)

</anti-answer>

#10


7  

* will not allow me to comment on hesselbom's answer (not enough reputation), so I'm adding my own...

*将不允许我评论hesselbom的答案(没有足够的声誉),所以我加入了我自己的…

$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).

这对我来说是最有效的,因为它还可以自动地消除前导(第二\s*)和拖尾(first \s*)空白,并跳过空白行(PREG_SPLIT_NO_EMPTY标志)。

-= OPTIONS =-

- = - =选项

If you want to keep leading whitespace, simply get rid of the second \s* and make it an rtrim() instead...

如果您想保持领先的空白,只需删除第二个\s*并将其改为rtrim()……

$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...

如果您需要保留空行,那么删除NULL(它只是一个占位符)和PREG_SPLIT_NO_EMPTY标志,就像这样…

$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)...

我看不出你有什么理由想要保留空白,所以我建议在这里留下第一个\s*。但是,如果你想要的是用新行来拆分(正如标题所示),这很简单(正如Jan Goyvaerts所提到的)……

$array = preg_split('/\R/', $text);

#11


3  

For anyone trying to display cronjobs in a crontab and getting frustrated on how to separate each line, use explode:

对于任何试图在crontab中显示cronjobs并对如何将每条线分隔开的人来说,使用爆炸:

$output = shell_exec('crontab -l');
$cron_array = explode(chr(10),$output);

using '\n' doesnt seem to work but chr(10) works nicely :D

使用“\n”似乎并不奏效,但chr(10)工作得很好:D。

hope this saves some one some headaches.

希望这能省去一些麻烦。

#12


2  

you can use this:

您可以使用:

 \str_getcsv($str,PHP_EOL);

#13


2  

You can do a $string = nl2br($string) so that your line break is changed to

您可以使用$string = nl2br($string),以便将换行符更改为。

<br />. 

This way it does not matter if the system uses \r\n or \n or \r

这样,如果系统使用\r\n或\ \r,就没有关系了。

Then you can feed it into an array:

然后你可以把它输入一个数组:

$array = explode("<br />", $string);

#14


1  

$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>

#15


0  

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

#16


0  

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)

#17


-4  

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

使用PHP爆发时,在字符串或行断点之间使用任何特殊字符都可以实现这一点。

#1


219  

You can use the explode function, using "\n" as separator :

您可以使用“\n”作为分隔符:

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

注意,您必须使用一个双引号字符串,所以\n实际上被解释为一个行中断。(详情请参阅手册页)

#2


249  

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

使用RegExp分割字符串,您可以将所有三个与\R匹配。

So for your problem:

对于你的问题:

$array = preg_split ('/$\R?^/m', $string);

That would match line breaks on Windows, Mac and Linux!

这将会在Windows, Mac和Linux上匹配换行符!

#3


240  

I've always used this with great success:

我一直都非常成功地使用这个方法:

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

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

(用最后的\r更新,谢谢@LobsterMan)

#4


32  

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

PHP已经知道当前系统的换行符。只用EOL常数。

explode(PHP_EOL,$string)

#5


23  

An alternative to Davids answer which is faster (way faster) is to use str_replace and explode.

Davids回答的另一个选择是使用str_replace和爆炸。

$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.

发生的情况是:由于换行符可以以不同的形式出现,所以我将替换\r\n、\n\r和\r和\n(保留原来的\n)。然后爆炸在\n,你有所有的线在一个数组。

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

我在这个页面的src上做了一个基准测试,并在for循环中对行进行了1000次的拆分:preg_replace使用了一个11秒的avg,然后使用了大约1秒的avg。

More detail and bencmark info on my forum

更多细节和bencmark信息在我的论坛。

#6


17  

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

大卫:方向很好,但你错过了。这工作对我来说:

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

#7


9  

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.

您不需要preg_*函数、preg模式或str_replace在内,等等。为了成功地用换行符将字符串分割成数组。在所有的场景中,无论是Linux/Mac还是m$,这都可以。

<?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.

PHP_EOL是服务器平台使用的行中断字符(s)的常量。

#8


8  

explode("\n", $str);

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

“(而不是)很重要,否则,换行不会被解释。”

#9


7  

<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:

正如其他答案所指定的那样,一定要使用爆炸,而不是拆分,因为在PHP 5.3.0分割的时候是不赞成的。以下不是你想要的方式:

$your_array = split(chr(10), $your_string);

LF = "\n" = chr(10), CR = "\r" = chr(13)

LF = "\n" = chr(10), CR = "\r" = chr(13)

</anti-answer>

#10


7  

* will not allow me to comment on hesselbom's answer (not enough reputation), so I'm adding my own...

*将不允许我评论hesselbom的答案(没有足够的声誉),所以我加入了我自己的…

$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).

这对我来说是最有效的,因为它还可以自动地消除前导(第二\s*)和拖尾(first \s*)空白,并跳过空白行(PREG_SPLIT_NO_EMPTY标志)。

-= OPTIONS =-

- = - =选项

If you want to keep leading whitespace, simply get rid of the second \s* and make it an rtrim() instead...

如果您想保持领先的空白,只需删除第二个\s*并将其改为rtrim()……

$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...

如果您需要保留空行,那么删除NULL(它只是一个占位符)和PREG_SPLIT_NO_EMPTY标志,就像这样…

$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)...

我看不出你有什么理由想要保留空白,所以我建议在这里留下第一个\s*。但是,如果你想要的是用新行来拆分(正如标题所示),这很简单(正如Jan Goyvaerts所提到的)……

$array = preg_split('/\R/', $text);

#11


3  

For anyone trying to display cronjobs in a crontab and getting frustrated on how to separate each line, use explode:

对于任何试图在crontab中显示cronjobs并对如何将每条线分隔开的人来说,使用爆炸:

$output = shell_exec('crontab -l');
$cron_array = explode(chr(10),$output);

using '\n' doesnt seem to work but chr(10) works nicely :D

使用“\n”似乎并不奏效,但chr(10)工作得很好:D。

hope this saves some one some headaches.

希望这能省去一些麻烦。

#12


2  

you can use this:

您可以使用:

 \str_getcsv($str,PHP_EOL);

#13


2  

You can do a $string = nl2br($string) so that your line break is changed to

您可以使用$string = nl2br($string),以便将换行符更改为。

<br />. 

This way it does not matter if the system uses \r\n or \n or \r

这样,如果系统使用\r\n或\ \r,就没有关系了。

Then you can feed it into an array:

然后你可以把它输入一个数组:

$array = explode("<br />", $string);

#14


1  

$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>

#15


0  

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

#16


0  

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)

#17


-4  

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

使用PHP爆发时,在字符串或行断点之间使用任何特殊字符都可以实现这一点。