1

I have a text file (similar to CSV concept) to parse and load into different columns.

I receive it from an external application I can't modify. It uses ";" as field separator but unfortunatly we can have the same char also inside some content.

Here a little sample:

Code;Name;Address;E_mail;Contact name
000001;FUTURAMA SNC;VIA BARBAPAPA, 1;[email protected];matteo futuro;
000006;FERRANTIBUS SRL;VIA TOPOLINO, 1;[email protected];nicola ferri;
000008;MORMORO SPA;VIA CICCETTI, 30;"[email protected]; [email protected]";panebianco gianpietro;

we use this code to parse the file

    $file = fopen("C:\\wamp\\www\\testcsv\\customers.csv","r");
$result ="";
$i=0;

while(! feof($file))
{
    $result[$i++]=  fgets($file);
}

for($j=1;$j<count($result);$j++){
    $tempData = preg_split("/[;]/",$result[$j]);
    print_r( $tempData );
}

as you can see, in the last line of the sample file, we have ";" char inside email field.... so it is read as another column separator and in the third record the email field is splitted as 2 column, with the result I have an additional column.

Is there any way, using regular expression to skip ; char if it is inside the "" chars?

Thanks in advance for the help

2
  • Why would you want to do that when PHP already has fgetcsv and explode? Commented Nov 17, 2014 at 9:55
  • $data = fgetcsv($file, 0, ';', '"', '"'); Commented Nov 17, 2014 at 10:00

1 Answer 1

1

You should not use regexpr to parse CSV files.

Use native PHP function http://php.net/manual/en/function.fgetcsv.php

This will solve your problem.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.