Hugo Mota
Hugo Mota

Reputation: 11567

how to manipulate line breaks in php?

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

Upvotes: 1

Views: 3561

Answers (2)

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146630

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

Upvotes: 3

Gumbo
Gumbo

Reputation: 655755

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

Upvotes: 10

Related Questions