0

I have a string like this:

'test', 'test', 'test, test', NULL, NULL, NULL, 123456789012, 0, '2017-02-17', FALSE

I want to explode it into an array.

But this gets messed up when a partial string contains a comma ('test, test').

How can I replace commas within a partial string into some other character? (so explode will work).

Apostrophes in the string must be contained, so str_getcsv() can not be used.

1
  • 2
    it's hard to answer your question correct when you change the requirement after someone already has answered ;-) Commented Feb 17, 2017 at 21:18

3 Answers 3

1

Here's my way:

$string = "'test', 'test', 'test, test, kk', NULL, NULL, NULL, 123456789012, 0, '2017-02-17', FALSE";

$array_tmp = explode(', ', $string);

$array = array();

$index_buffer = NULL;
$index = 0;
foreach($array_tmp as $value) {
    // Check if we need to append to buffered entry
    if($index_buffer !== NULL){
        $array[$index_buffer] .= ', ' . $value;
        if($value[strlen($value) - 1] === "'"){
            $index_buffer = NULL;
        }
        continue;
    }

    // Check if it's not ended string
    if(is_string($value) && $value[0] === "'"  && $value[strlen($value) - 1] !== "'"){
        // It is not ended, set this index as buffer
        $index_buffer = $index;
    }

    // Save value
    $array[$index] = $value;
    $index++;
}

echo '<pre>' . print_r($array, true);

Output:

Array
(
    [0] => 'test'
    [1] => 'test'
    [2] => 'test, test, kk'
    [3] => NULL
    [4] => NULL
    [5] => NULL
    [6] => 123456789012
    [7] => 0
    [8] => '2017-02-17'
    [9] => FALSE
)

Or this may be more suitable but you lose quotes, and I guess, if your input string doesn't respect all csv standards, you could have border effects since str_getcsv handles more things than this quote issue:

str_getcsv($string, ",", "'");
Sign up to request clarification or add additional context in comments.

Comments

1

You can do this manually and improve it to support more cases... Try something like this:

$arr = array();
$arr[0] = "";
$arrIndex = 0;
$strOpen = false;
for ($i = 0; $i < mb_strlen($str); $i++){
  if ($str[$i] == ',') {
    if ($strOpen == false) {
       $arrIndex++;
       $arr[$arrIndex] = "";
    }
    else {
       $arr[$arrIndex] .= $str[$i];
    }
  }
  else if ($str[$i] == '\'') {
    $strOpen = !$strOpen;
  }
  else {
    $arr[$arrIndex] .= $str[$i];
  }
}

Result:

Array
(
    [0] => test
    [1] =>  test
    [2] =>  test, test
    [3] =>  NULL
    [4] =>  NULL
    [5] =>  NULL
    [6] =>  123456789012
    [7] =>  0
    [8] =>  2017-02-17
    [9] =>  FALSE
)

Note: it will keep "empty" spaces around comas

Comments

1

Try using str_getcsv

str_getcsv($string, ",", "'");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.