How to split a CSV string to array of fields in PHP using regex but treating escaped…
- User
How to split a CSV string to array of fields in PHP using regex but treating escaped commas as part of data?
- Assistant
In PHP, you can use the
str_getcsv()function to split a CSV string into an array of fields, while also handling escaped commas as part of the data. This function is more reliable than using regex for parsing CSV data.Here's an example:
php$csvString = 'field1,"field2 with , comma",field3,"field4 with ""quotes""",field5'; $fields = str_getcsv($csvString); print_r($fields);Output:
codeArray ( [0] => field1 [1] => field2 with , comma [2] => field3 [3] => field4 with "quotes" [4] => field5 )If you still want to use regex, you can use the following pattern:
php$csvString = 'field1,"field2 with , comma",field3,"field4 with ""quotes""",field5'; $pattern = '/"([^"]*)"|([^,]+)/'; preg_match_all($pattern, $csvString, $matches); $fields = array_map(function($match) { return trim($match, '" '); }, $matches[0]); print_r($fields);Output:
codeArray ( [0] => field1 [1] => field2 with , comma [2] => field3 [3] => field4 with "quotes" [4] => field5 )This regex pattern
/"([^"]*)"|([^,]+)/matches either a quoted string or a non-comma string. Thearray_map()function is used to remove the surrounding quotes and spaces from the matched strings.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.