PHP: Explode textarea lines as separate array element
Asked Answered
S

3

6

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!

Schlicher answered 20/2, 2012 at 14:23 Comment(4)
If you are so smart, tell me, what is wrong here?Schlicher
Did you mean to write explode("\n", $numbers); or explode("\r\n", $numbers);? Or are you actually writing both statements right next to each other as a single line like that?Swamy
You should post a little more code, the HTML form as well as a little more surrounding code.Snoddy
explode("\r\n", $numbers); suppose to work.. well it is working for me.Nichy
C
10

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));
Chartres answered 20/2, 2012 at 14:36 Comment(1)
you're right, of course. User submitted data may not translate to the system EOL. comment withdrawn.Swamy
H
11

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

This should do it.

Handcraft answered 20/2, 2012 at 14:29 Comment(0)
C
10

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));
Chartres answered 20/2, 2012 at 14:36 Comment(1)
you're right, of course. User submitted data may not translate to the system EOL. comment withdrawn.Swamy
N
3

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

?>
Nottingham answered 5/6, 2016 at 14:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.