fork download
  1. <?php
  2.  
  3. $input = "'54\",\"34',34,\"ab,ac\",10,20";
  4. echo "<pre>$input\n\n";var_dump(my_parser($input)); echo "</pre>\n\n";
  5. $input = "ab$,wdf;tt5,4h56;73t2";
  6. echo "<pre>$input\n\n";var_dump(my_parser($input)); echo "</pre>\n\n";
  7. $input = "'54\",\"'6'34',34,,\"ab,ac\",10,20";
  8. echo "<pre>$input\n\n";var_dump(my_parser($input)); echo "</pre>\n\n";
  9.  
  10. function my_parser($input)
  11. {
  12. $delimeters = [',', ';'];
  13. $quotes = ['"', '\''];
  14. $currentQuote = null;
  15. $currentArg = '';
  16. $args = [];
  17.  
  18. $len = strlen($input);
  19. for ($i=0; $i<$len; $i++) {
  20. $currentSymbol = $input[$i];
  21.  
  22. if (!empty($currentQuote)) { // we're in quotes
  23. if ($currentQuote === $currentSymbol) { // and quote matched
  24. $currentQuote = null; // so quote closed!
  25. } else { // quoted quote, lol
  26. $currentArg .= $currentSymbol; // let it go, it's string
  27. }
  28. } else { // not in quotes
  29. if (in_array($currentSymbol, $quotes)) { // check if symbol is quote
  30. $currentQuote = $currentSymbol; // and remember this quote
  31. } elseif (in_array($currentSymbol, $delimeters)) { // check for delimeter
  32. if (strlen($currentArg)) {
  33. $args[] = $currentArg; // it's end of valid argument, yeah!
  34. $currentArg = '';
  35. }
  36. } else { // simple symbol, pass it
  37. $currentArg .= $currentSymbol; // let it go, it's string
  38. }
  39. }
  40. }
  41. if (strlen($currentArg)) {
  42. $args[] = $currentArg;
  43. }
  44. return $args;
  45. }
  46.  
Success #stdin #stdout 0.02s 52472KB
stdin
Standard input is empty
stdout
<pre>'54","34',34,"ab,ac",10,20

array(5) {
  [0]=>
  string(7) "54","34"
  [1]=>
  string(2) "34"
  [2]=>
  string(5) "ab,ac"
  [3]=>
  string(2) "10"
  [4]=>
  string(2) "20"
}
</pre>

<pre>ab$,wdf;tt5,4h56;73t2

array(5) {
  [0]=>
  string(3) "ab$"
  [1]=>
  string(3) "wdf"
  [2]=>
  string(3) "tt5"
  [3]=>
  string(4) "4h56"
  [4]=>
  string(4) "73t2"
}
</pre>

<pre>'54","'6'34',34,,"ab,ac",10,20

array(5) {
  [0]=>
  string(8) "54","634"
  [1]=>
  string(2) "34"
  [2]=>
  string(5) "ab,ac"
  [3]=>
  string(2) "10"
  [4]=>
  string(2) "20"
}
</pre>