tags:

views:

93

answers:

4

The string input comes from textarea where users are supposed to enter every single item on a new line.

When processing the form, it is easy to explode the textarea input into an array of single items like this:

$arr = explode("\n", $textareaInput);

It works fine but I am worried about it not working correctly in different systems (I can currently only test in Windows). I know newlines are represented as \r\n or as just \r across different platforms. Will the above line of code also work correctly under Linux, Solaris, BSD or other OS?

+4  A: 

$arr = preg_split( "/[\n\r]+/", $textareaInput );

meouw
+6  A: 

Hey.

You can use preg_split to do that.

$arr = preg_split('/[\r\n]+/', $textareaInput);

It splits it on any combination of the \r or \n characters. You can also use \s to include any white-space char.

Edit
It occurred to me, that while the previous code works fine, it also removes empty lines. If you want to preserve the empty lines, you may want to try this instead:

$arr = preg_split('/(\r\n|[\r\n])/', $textareaInput);

It basically starts by looking for the Windows version \r\n, and if that fails it looks for either the old Mac version \r or the Unix version \n.

For example:

<?php
$text = "Windows\r\n\r\nMac\r\rUnix\n\nDone!";
$arr = preg_split('/(\r\n|[\r\n])/', $text);
print_r($arr);
?>

Prints:

Array
(
    [0] => Windows
    [1] => 
    [2] => Mac
    [3] => 
    [4] => Unix
    [5] => 
    [6] => Done!
)
Atli
Not every newline is accompanied by a \r, I think you write too much code for windows.
Rook
@Michael Brooks. It is a regular expression. the `[\r\n]` means either `\r` or `\n`. It looks for any combination of the two characters... And no, you are incorrect. I do in fact prefer working on Linux, and I am well aware of the differences.
Atli
+3  A: 

'\r' by itself as a line terminator is an old convention that's not really used anymore (not since OSX which is Unix based).

Your explode will be fine. Just trim off the '\r' in each resulting element for the Windows users.

Frank Krueger
+1  A: 

You can normalize the input:

<?php

$foo = strtr($foo, array(
    "\r\n" => "\n",
    "\r" => "\n",
    "\n" => "\n",
));

?>

Alternatively, you can explode with regular expressions:

<?php

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

?>
Álvaro G. Vicario