Search code examples
phpnewlineexplodemultiline

How to split a multiline string on newlines?


I'm having a problem with this string

string(313) "
12312312312312312
12312312312312312
12312312312312312
12312312312312312
12312312312312312
12312312312312312
12312312312312312
12312312312312312
12312312312312312
12312312312312312"

The result i want is = array("12312312312312312","12312312312312312") etc...

I want to separate the entrys to put into the array, I tried all this methods with php:

$numbers = explode("\n",$numbers); 

$numbers = explode(" ",$numbers);

$numbers = explode("<br>",$numbers);  

$numbers = str_replace("\n", " ", "<br>", $numbers)

Solution

  • You need to explode() with new line (PHP_EOL):

    $numbers= array_filter(explode(PHP_EOL, $numbers)); // PHP_EOL used for new line
    
    print_r($numbers);
    

    Output:-https://3v4l.org/0OH4N

    Note:- array_filter() used to remove empty,null value indexes from array