Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Explode textarea lines as separate array element

I have a textarea that contains phone numbers, each number in a separate line. I want to explode that string into an array using

explode("\n", $numbers);

or

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

This is not working. Please, help me. Thanks!

like image 944
Sergiu Svet Avatar asked Feb 20 '12 14:02

Sergiu Svet


3 Answers

$records = preg_split('/[\r\n]+/', $mystring, -1, PREG_SPLIT_NO_EMPTY);

This should do it.

like image 164
Frederick Behrends Avatar answered Oct 20 '22 13:10

Frederick Behrends


As the manual states: Returns an array of strings.

So you'll have to store the result. The or won't work that way either. If you don't know whether the input will contain \n or \r\n, you could do a replace to replace \r by an empty string, then explode on \n.

This should do the trick:

$numbers = explode("\n", str_replace("\r", "", $numbers));
like image 29
CodeCaster Avatar answered Oct 20 '22 11:10

CodeCaster


Use this

<?php

 $input = $_POST['textarea_name'];
 $new_array = array_values(array_filter(explode(PHP_EOL, $input)));

 // explode -> convert textarea to php array (that lines split by new line)
 // array_filter -> remove empty lines from array
 // array_values -> reset keys of array

?>
like image 3
Abdo-Host Avatar answered Oct 20 '22 11:10

Abdo-Host