Split() by newline and return using PHP

How to create an array by using the split() function on multiple newlines and returns.

Introduction:

I was having a problem trying to split a string of multiple lines from an online form using the flowing code:

<?php
   $arry_names = split("\n", $names);
?>

This was producing an unexpected line break. I searched the web to see if anyone had the same problem and found that I needed to check for “returns” (\r) also. So now when I’m splitting data by lines, I use the following code:

<?php
   $arry_names = split("[\n|\r]", $names);
?>

You may also like...

6 Responses

  1. decko says:

    I think it's enough using split("[\n]",$names);

  2. Fred says:

    split (“[\r\n|\n]”, $array); is the solution!

  3. Pan Panpan says:

    what about

    split(‘[\r\n|\r|\n]’,$array)

    ?

    Anyway, thanks for your help! I really appreciate.

  4. Pan Panpan says:

    Sorry,

    php says:

    This function [split] has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

    Use preg_split instead.

    greets.

  5. Tim says:

    Also, your regexp is total BS. You’re confusing (\r|\n) with [\r\n]. [] doesn’t need |, since it’s for single characters. The 100% sure-fire cross-platform separator is (?:\r\n|\r|\n), which can be abbreviated to (?:\r\n?|\n).

  6. When splitting an empty string you don’t get an empty array, instead you get an array with an empty string as it’s only element. To improve Tim’s answer here is a function:

    function split_lines ($string) {
    $lines = preg_split(“/\r\n|\r|\n/”, $string);
    if (count($lines) == 1 && !$lines[0]) {
    return array();
    }
    return $lines;
    }

Leave a Reply