0

I've never actually used arrays before, as I've never had to so far (a simple variable has been enough for me), however now I've created a form with a text-area that is meant to POST multiple urls through to my PHP script.

What I want to do is use a line-break in the visitors input to act as a separator for an array input.

For example, the visitor inputs 90 lines of text (all url's), the array breaks each one into a list of 90, and creates an array value for each one.

Any info, advice or comments would be greatly appreciated :)!

Fireworksable
  • 343
  • 1
  • 5
  • 14

3 Answers3

1

Look at http://www.php.net/manual/en/function.preg-split.php and as delimiter use new line sign

or see PHP REGEX - text to array by preg_split at line break

be careful about using just \r or \n because every operating system has "new line" defined another way
see answer by Tgr on SO question PHP REGEX - text to array by preg_split at line break

Community
  • 1
  • 1
Marek Sebera
  • 39,650
  • 37
  • 158
  • 244
  • Regex aren't really needed here I think. When regex aren't really needed don't use them – PeeHaa Aug 06 '11 at 15:31
  • regex is needed because new line is somethimes another than just `\n` so it is better to use preg_replace and `\R` switch to handle them all – Marek Sebera Aug 06 '11 at 15:34
  • it is? Let me run a test. 1 sec. If you're right you're right :) – PeeHaa Aug 06 '11 at 15:35
  • I have a linux based server, so "\n" acts as a line break, unless you're saying that the visitors "OS" itself determines the line break? – Fireworksable Aug 06 '11 at 15:37
  • 1
    @Fireworksable: what if you need to change your hosting for some reason. Even if you don't coding should always be done by writing code that will 'always' work – PeeHaa Aug 06 '11 at 15:46
1

Not 100% percent sure what line breaks are used, e.g.:

Windows uses \r\n Linux uses \n (old) Macs used \r

However if you know this you can simply do:

$urls = explode("\n", $_POST['urls']);

EDIT

Actually after testing using regex IS faster than first doing a str_replace() and explode.

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
  • Thanks :). Exactly what I was looking for, I've seen the explode function used before, but never had an idea of what it actually did). – Fireworksable Aug 06 '11 at 15:36
  • 2
    Use str_replace and your explode will work every time: `$urls = str_replace(array("\r\n", "\r"), "\n", $_POST['urls']);` – Glass Robot Aug 06 '11 at 15:37
-1

Use explode

$array=explode("\n",$_POST['textarea']);
RiaD
  • 46,822
  • 11
  • 79
  • 123