Skip to content

Instantly share code, notes, and snippets.

@Freeaqingme
Created June 15, 2012 22:15
Show Gist options
  • Save Freeaqingme/2938966 to your computer and use it in GitHub Desktop.
Save Freeaqingme/2938966 to your computer and use it in GitHub Desktop.
Input:
application/vnd.foobar+html;q=1; version="2\3\""; level="foo, bar", text/json;level=1, text/xml;level=2;q=0.4
Goal: Explode string by the comma's it contains
Contraints:
* commas between quotes (") dont count
* quotes may be escaped
Expected output:
* application/vnd.foobar+html;q=1; version="2\3\""; level="foo, bar"
* text/json;level=1
* text/xml;level=2;q=0.4
My futile attempt:
'#\s*((?<!\\\\)"[^"]*"),|,+#
Current output:
* "application/vnd.foobar+html;q=1; version="2\3\""; level=
* "foo, bar"
* text/json;level=1
* text/xml;level=2;q=0.4
Environment:
php5.3+
preg_split('#\s*((?<!\\\\)"[^"]*"),|,+#', $str, -1 , PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
Code:
<?php
$str = 'application/vnd.foobar+html;q=1; version="2\3\""; level="foo, bar", text/json;level=1, text/xml;level=2;q=0.4';
echo $str.PHP_EOL.PHP_EOL;
$res = preg_split('#\s*((?<!\\\\)"[^"]*"),|,+#', $str, -1 , PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
var_dump($res);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment