1

I have this little problem where i'm getting the content of a CSV using PHP, which works just fine, but then i try to split it using preg_split like this:

$csv = file_get_contents($file);
$content= preg_split('/\r\n|\r|\n/', $csv);

It does split the content but it also adds an empty array key at the end of the array(cause of that new line) so the array will basicly look like this:

array(
    [0] => some;content;here;
    [1] => some;other;content;
    [3] => 
)

Basicaly my question is: how do i write that regular expression to avoid splitting the last occurrence of that pattern?(and also afterwords i want to split those array keys by ; and again i get an empty array key cause there is a ; at the end of every string

Thank you for your time! X_X

emma
  • 761
  • 5
  • 20
  • 1
    [Trim](http://php.net/manual/pl/function.trim.php) the string before splitting. `preg_split('/\R/', trim($csv))` – Wiktor Stribiżew Aug 09 '18 at 07:47
  • 1
    `$content= array_filter( preg_split('/\r\n|\r|\n/', $csv) );` ? to filter empty elements from array. But why not use some of the purpose built methods for dealing with CSV files? – Professor Abronsius Aug 09 '18 at 07:47
  • 4
    Is there a reason not to use phps csv-handling functions? (`fgetcsv(...)`) – Tom Regner Aug 09 '18 at 07:48
  • Tom and Ram and Wik thanks a lot, the only reason for not using some of csv-handling functions was my limited knowledge :O but nah it's hard in school X_X :D – emma Aug 09 '18 at 07:59
  • Have a read of https://stackoverflow.com/questions/9139202/how-to-parse-a-csv-file-using-php – Nigel Ren Aug 09 '18 at 07:59

1 Answers1

2

Have you tried fgetcsv(); instead? No need to manually parse the file. http://php.net/manual/en/function.fgetcsv.php

Marinus
  • 521
  • 2
  • 15