fork(3) download
  1. <?php
  2.  
  3. $source=<<<EOT
  4. field a,field b,field c,field d,field e
  5. 1,2,3,4,5
  6. test,computer,I like
  7. pie,4,8
  8. 123,456,"7
  9.  
  10. 8
  11.  
  12. 9",10,11
  13. a,b,c,d,e
  14. EOT;
  15.  
  16. function add_quotes($matches) {
  17. return preg_replace('~(?<=^|,)(?>[^,"\r\n]+\r?\n[^,]*)(?=,|$)~',
  18. '"$0"',
  19. $matches[0]);
  20. }
  21.  
  22. preg_match_all('~\G,?[^,\r\n]++~', $source, $cols);
  23.  
  24. $row_regex = '~^(?:(?:(?:"[^"*]")+|[^,]*)(?:,|$)){' . count($cols[0]) . '}$~m';
  25.  
  26. $result=preg_replace_callback($row_regex, 'add_quotes', $source);
  27.  
  28. print($result);
  29.  
  30. ?>
Success #stdin #stdout 0.02s 13112KB
stdin
Standard input is empty
stdout
field a,field b,field c,field d,field e
1,2,3,4,5
test,computer,"I like
pie",4,8
123,456,"7

8

9",10,11
a,b,c,d,e