2

My textarea ( $_POST['data'] ) contains 10 strings, each separated by a new line (\n). For example:

January
February
March
April
May
Jun
July
August
September
November

In PHP, how can I select only the first 5 elements from this $_POST['data']?

I tried:

$_POST['data'] = array_slice(explode("\n", $_POST['data']), 0, 5);

but it doesn't seem to work..

Tom
  • 1,200
  • 17
  • 31
  • Try using this pregsplit instead of explode: http://stackoverflow.com/questions/3997336/explode-php-string-by-new-line – Joseph Evans Sep 01 '16 at 18:59
  • So something like this: ? $_POST['data'] = array_slice(preg_split('/\n|\r/', $_POST['data'], -1, PREG_SPLIT_NO_EMPTY), 0, 5); I tried it but it doesn't work.. – Tom Sep 01 '16 at 19:04
  • 1
    Probably more like: $_POST['data'] = array_slice(preg_split("/\\r\\n|\\r|\\n/", $_POST['data']), 0, 5); – Joseph Evans Sep 01 '16 at 19:09
  • I tried it and it seems $_POST['data'] still has all 10 elements instead of first 5... – Tom Sep 01 '16 at 19:15
  • The code shown in the question works for me. What browser are you using? – Don't Panic Sep 01 '16 at 19:22
  • FWIW, [the spec](https://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2.1) says the separator shall be `\r\n`. – bishop Sep 01 '16 at 19:36
  • You're right, I think it works now.. – Tom Sep 01 '16 at 19:43

1 Answers1

0

Try

<?php     
if (isset($_POST)){
$str = $_POST['data'];

$lines=explode("\n", $str);

for($i = 0; $i < 5; ++$i) {     
     echo $lines[$i];//just get the list
     echo "$lines[$i]"."<br>";//break the lines with br
     echo "$lines[$i]"."\n";//break the lines with nr
    }
 }
?>
Omari Victor Omosa
  • 2,682
  • 1
  • 23
  • 41