-1

Using: PHP 7

I need to parse a string from a CSV file and return the values in an array. I'm using preg_match_all, but have had no luck so far.

This is the string:

"494","1","41","2009-05-18","NULL","0","3","JONES,ZACK ZX",""

This is the PHP code:

<?php
 $s = '"494","1","41","2009-05-18","NULL","0","3","JONES,ZACK ZX",""' ;

 $p =  '(?<=^|,)(?:[^,"]+|")?(?=,|$)|(?<=^|,)".*?"(?=,|$)';

 $m = Array();

 $e = preg_match_all($p, $s, $m);

After it is executed, the $m array should contain all the string values, without the double-quote string enclosure character.

Would appreciate any help in getting the correct regular expression to use.

4
  • 1
    Can I ask why you're using a regular expression for this, rather than something like str_getcsv? Commented Apr 6, 2020 at 12:41
  • @iainn I tried str_getcsv, it did not produce the correct result. Commented Apr 6, 2020 at 12:42
  • 1
    Regex is not the tool for this. There's no reason why the built-in CSV parsing features of PHP would produce unintended results on a dataset as simple as the one you've provided. Trying to re-create a CSV parser in regex (especially to include all edge cases and escape sequences) is like re-inventing a perfectly good wheel. Commented Apr 6, 2020 at 12:44
  • @iainn I gave str_getcsv another try and it worked! I'll post my answer below. Commented Apr 6, 2020 at 12:45

1 Answer 1

0

Following iainn's suggestion, I tried str_getcsv, and it worked!

Here is the answer:

$m = str_getcsv($s, ",", "\"");
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.