-1

What is the correct regular expression to archive the desired result? Hence, empty fields in $str may or may not be surrounded by ""

$str='"Value","Value, containing delimiter","","End"';
$regEx="/,/";
print_r(preg_split($regEx,$str));

Output:

Array
(
    [0] => "Value"
    [1] => "Value
    [2] =>  containing delimiter"
    [3] => ""
    [4] => "End"
)

Desired output:

Array
(
    [0] => "Value"
    [1] => "Value, containing delimiter"
    [2] => ""
    [3] => "End"
)
solid.py
  • 2,782
  • 5
  • 23
  • 30
jamacoe
  • 519
  • 4
  • 16

1 Answers1

0

I think you are looking for something like this:

$str='"Value","Value, containing delimiter","","End"';
$regEx='/,s*(?=([^"]*"[^"]*")*[^"]*$)/'; 
print_r(preg_split($regEx,$str));

When run, the output is:

Array ( 
        [0] => "Value" 
        [1] => "Value, containing delimiter" 
        [2] => "" 
        [3] => "End"
)
solid.py
  • 2,782
  • 5
  • 23
  • 30
  • 1
    It will give an undesired result on `'"Value",,"Value, containing delimiter","","End"'` if I understood OP correctly – Eugene Anisiutkin Mar 06 '20 at 12:21
  • @EugeneAnisiutkin I need an clarification on that from OP, since I genuinely think he made a mistake when typing / copy-pasting the input string. – solid.py Mar 06 '20 at 12:22
  • ok, got it: $regEx='/,\s*(?=([^"]*"[^"]*")*[^"]*$)/'; Thanks to @wiktor-stribiżew – jamacoe Mar 06 '20 at 12:35
  • I found some interesting results using this solution not sure how they fit OP's view though. An example code is [Here](http://sandbox.onlinephpfunctions.com/code/7eb15b1e60e91514b5424c2577cc7315b7a992cc) also a very slight mod to original rexex removes the "interesting results". An updated exaple is [Here](http://sandbox.onlinephpfunctions.com/code/568a6477cfd6ea994d9e2f1ac121587dc650e10f). – Eugene Anisiutkin Mar 06 '20 at 12:42
  • To the downvoter, run the code, and see that it works exactly as the OP requested. – solid.py Mar 07 '20 at 08:57