按换行符分割字符串

发布于 2024-08-05 10:36:14 字数 246 浏览 8 评论 0原文

我有一个带有换行符的字符串。我想将该字符串转换为数组,并且对于每个新行,跳转数组中的一个索引位置。

如果字符串是:

My text1
My text2
My text3

我想要的结果是这样的:

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

I have a string with new line characters. 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
)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

那支青花 2024-08-12 10:36:14

我一直使用它取得了巨大的成功:(

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

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

I've always used this with great success:

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

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

双手揣兜 2024-08-12 10:36:14

您可以使用 explode 函数,使用“\n" 作为分隔符:

$your_array = explode("\n", $your_string_from_db);

例如,如果您有这段代码:

$str = "My text1\nMy text2\nMy text3";
$arr = explode("\n", $str);
var_dump($arr);

您将得到以下输出:

array
  0 => string 'My text1' (length=8)
  1 => string 'My text2' (length=8)
  2 => string 'My text3' (length=8)

请注意,您必须使用 double-带引号的字符串,因此 \n 实际上被解释为换行符。

(有关更多详细信息,请参阅该手册页。)

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

梦幻之岛 2024-08-12 10:36:14

换行符在不同平台上的定义不同,\r\n、\r 或 \n。

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

因此对于您的问题:

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

这将匹配 Windows、Mac 和 Linux 上的换行符!

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!

旧人 2024-08-12 10:36:14

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

explode(PHP_EOL,$string)

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

explode(PHP_EOL,$string)
裸钻 2024-08-12 10:36:14

Davids answer 更快(更快)的替代方法是使用 str_replace爆炸

$arrayOfLines = explode("\n",
                    str_replace("\r\n","\n",$str)
            );

发生的事情是:
由于换行符可以有不同的形式,因此我将 str_replace \r\n、\n\r 和 \r 替换为 \n(并保留原始 \n)。
然后在 \n 上爆炸,你就得到了一个数组中的所有行。

我对此页面的 src 进行了基准测试,并在 for 循环中将行拆分了 1000 次,并且:
preg_replace 平均耗时 11 秒
str_replace &爆炸平均耗时约1秒

更多详细信息和基准信息请参见我的论坛

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

世态炎凉 2024-08-12 10:36:14

大卫有一个 < em>很好的方向,但它错过了\r。这对我有用:

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

David has a great direction, but it missed \r. This worked for me:

$array = preg_split("/(\r\n|\n|\r)/", $string);
听闻余生 2024-08-12 10:36:14

您不需要 preg_* 函数、preg 模式、str_replace 等来成功通过换行符将字符串分解为数组。在所有场景下,无论是 Linux、Mac 还是 Windows,都可以。

<?php
    $array = explode(PHP_EOL, $string);
    // ...
    $string = implode(PHP_EOL, $array);
?>

PHP_EOL 是一个常量,保存服务器平台使用的换行符。

You don't need preg_* functions, preg patterns, str_replace within, etc. in order to successfully break a string into array by newlines. In all scenarios, be it Linux, Mac, or Windows, 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.

甜`诱少女 2024-08-12 10:36:14

使用:
$array = preg_split('/\s*\R\s*/', trim($text), NULL, PREG_SPLIT_NO_EMPTY);

这对我来说效果最好,因为它还自动消除前导(第二个 \s*)和尾随(第一个 \s*)空白,并跳过空白行(PREG_SPLIT_NO_EMPTY 标志)。

选项

如果你想保留前导空白,只需去掉第二个 \s* 并将其改为 rtrim() ...

$array = preg_split('/\s*\R/', rtrim($text), NULL, PREG_SPLIT_NO_EMPTY);

如果你需要保留空行,去掉 NULL (它只是一个占位符)并PREG_SPLIT_NO_EMPTY 标志,就像这样...

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

或者保留前导空格和空行...

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

我看不出有任何理由要保留尾随空格,所以我建议将第一个 \s* 留在那里。但是,如果您想要的只是按换行符分割(如标题所示),那么这个很简单(如Jan Goyvaerts 提到)...

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

Use:
$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);
旧城烟雨 2024-08-12 10:36:14

此页面上有相当多的直接和间接答案,以及评论中的一些好的建议,但没有一个答案代表我在自己的项目中编写的内容。

PHP 转义序列 \R 文档:https://www.php.net/manual/en/regexp.reference.escape.php#:~:text=line%20break,\r\n

代码:(Demo)

$string = '
My text1

My text2


My text3


';

var_export(
    preg_split('/\R+/', $string, 0, PREG_SPLIT_NO_EMPTY)
);

输出:

array (
  0 => 'My text1',
  1 => 'My text2',
  2 => 'My text3',
)

OP 没有提到从行中修剪水平空白字符,因此有在变量(与系统无关)新行上爆炸时,不需要删除 \s\h

虽然 PHP_EOL 是明智的建议,但当换行序列来自另一个操作系统时,它缺乏适当地分解字符串的灵活性。

使用非正则表达式爆炸往往不太直接,因为它需要字符串准备。此外,如果有不需要的空白行需要删除,爆炸后可能需要清理。

使用 \R+(一个或多个连续的换行序列)和 PREG_SPLIT_NO_EMPTY 函数标志将在单个简洁的函数调用中提供无间隙的索引数组。有些人对正则表达式有偏见,但这是为什么应该使用正则表达式的完美案例。如果出于合理的原因需要考虑性能(例如,您正在处理数十万个数据点),那么请继续投资基准测试和微优化。除此之外,只需使用这一行代码即可使您的代码简洁、健壮且直接。

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.

七颜 2024-08-12 10:36:14
explode("\n", $str);

"(而不是 ')非常重要,否则换行符将不会被解释。

explode("\n", $str);

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

乄_柒ぐ汐 2024-08-12 10:36:14
<anti-answer>

正如其他答案所指定的,请务必使用 explode 而不是 split,因为从 PHP 5.3.0 开始 split 已被弃用。即以下不是您想要的方式:

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

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

</anti-answer>
<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>
冬天旳寂寞 2024-08-12 10:36:14

使用:

$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";
}

真实数组:

$str = "My text1\nMy text2\nMy text3";
$arr = explode("\n", $str);

$array = array();

foreach ($arr as $line) { // loop line by line and convert into array
    $array[] = $line;
};

print_r($array); // display all value

echo $array[1]; // display index 1

在线嵌入:

body, html, iframe {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
<iframe src="https://ideone.com/vE1gst" ></iframe>

Use:

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

foreach ($arr as $line) { // loop line by line and convert into array
    $array[] = $line;
};

print_r($array); // display all value

echo $array[1]; // display index 1

Embed online:

body, html, iframe {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
<iframe src="https://ideone.com/vE1gst" ></iframe>

濫情▎り 2024-08-12 10:36:14

对于任何试图在 crontab 中显示 cronjobs 并对如何分隔每一行感到沮丧的人,请使用explode:

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

使用 '\n' 似乎不起作用,但 chr(10) 工作得很好:D

希望这可以减轻一些人的麻烦。

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.

北渚 2024-08-12 10:36:14

这就是我的方式:

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

这也将跳过所有空行。

That's my way:

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

This also will skip all empty lines too.

醉南桥 2024-08-12 10:36:14

你可以使用这个:

 str_getcsv($str, PHP_EOL);

You can use this:

 str_getcsv($str, PHP_EOL);
澜川若宁 2024-08-12 10:36:14

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

<br />. 

这样,系统使用 \r\n 或 \n 或 \r 并不重要

然后您可以将其送入数组:

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

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);
叹倦 2024-08-12 10:36:14

我在 PHP 文档中找到了这一点:

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

I picked this up in the PHP documentation:

<?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);
?>
终弃我 2024-08-12 10:36:14

仅使用“基本”包也是简单情况的解决方案:

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

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)
何以畏孤独 2024-08-12 10:36:14

这个方法总是对我有用:

$uniquepattern = "gd$#%@&~#" // Any set of characters which you don’t expect to be present in user input $_POST['text']. Better use at least 32 characters.
$textarray = explode($uniquepattern, str_replace("\r", "", str_replace("\n", $uniquepattern, $_POST['text'])));

This method always works for me:

$uniquepattern = "gd$#%@&~#" // Any set of characters which you don’t expect to be present in user input $_POST['text']. Better use at least 32 characters.
$textarray = explode($uniquepattern, str_replace("\r", "", str_replace("\n", $uniquepattern, $_POST['text'])));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文