php中如何处理换行符?

发布于 2024-10-07 06:18:07 字数 230 浏览 5 评论 0原文

我想知道是否有办法在 PHP 中操作换行符。例如,明确告诉在 explode() 函数中选择使用哪种换行符(LF、CRLF...)。

大概是这样的:

$rows = explode('<LF>', $list);
//<LF> here would be the line break

有人可以帮忙吗?谢谢 (:

I wanted to know if there's a way to manipulate line breaks within PHP. Like, to explicitly tell what kind of line break to select (LF, CRLF...) for using in an explode() function for instance.

it would be something like that:

$rows = explode('<LF>', $list);
//<LF> here would be the line break

anyone can help? thanks (:

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

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

发布评论

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

评论(2

晚风撩人 2024-10-14 06:18:07

LFCR只是代码点0x0A(换行)和0x0D(回车 >) ASCII 格式。您可以按字面意思编写它们,也可以使用适当的转义序列:

"\x0A" "\n"  // LF
"\x0D" "\r"  // CR

请记住使用 双引号单引号 只知道转义序列 \\\'

CRLF 将只是两个字符的串联。因此:

$rows = explode("\r\n", $list);

如果您想在 CR LF 处进行拆分,您可以使用正则表达式进行拆分:

$rows = preg_split("/[\r\n]/", $list);

并跳过空行(即多个换行符的序列):

$rows = preg_split("/[\r\n]+/", $list);

LF and CR are just abbreviations for the characters with the code point 0x0A (LINE FEED) and 0x0D (CARRIAGE RETURN) in ASCII. You can either write them literally or use appropriate escape sequences:

"\x0A" "\n"  // LF
"\x0D" "\r"  // CR

Remember using the double quotes as single quotes do only know the escape sequences \\ and \'.

CRLF would then just be the concatenation of both characters. So:

$rows = explode("\r\n", $list);

If you want to split at both CR and LF you can do a split using a regular expression:

$rows = preg_split("/[\r\n]/", $list);

And to skip empty lines (i.e. sequences of more than just one line break characters):

$rows = preg_split("/[\r\n]+/", $list);
执妄 2024-10-14 06:18:07

根据您的需要,我可以想到一些可能性:

  • 选择 EOL 样式并指定确切的字符: "\r\n"
  • 选择 PHP 运行平台的 EOL 并使用PHP_EOL 常量
  • 使用正则表达式: preg_split('/[\r\n]+/', ...)
  • 使用可以自动检测行结尾的函数: file()
  • 在分解之前对输入字符串进行标准化:

    $text = strtr($text, array(
        "\r\n" =>; PHP_EOL,
        “\r” => PHP_EOL,
        “\n” => PHP_EOL,
    ));
    

Some possibilities I can think of, depending on your needs:

  • Pick an EOL style and specify the exact character(s): "\r\n"
  • Choose the EOL of the platform PHP runs on and use the PHP_EOL constant
  • Use regular expressions: preg_split('/[\r\n]+/', ...)
  • Use a function that can autodetect line endings: file()
  • Normalize the input string before exploding:

    $text = strtr($text, array(
        "\r\n" => PHP_EOL,
        "\r" => PHP_EOL,
        "\n" => PHP_EOL,
    ));
    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文