2017-02-17 107 views
0

内更换逗号我有一个这样的字符串:部分字符串

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

我想它爆炸成一个阵列。

但是,当部分字符串包含逗号('test,test')时,会发生混乱。

如何将部分字符串中的逗号替换为其他字符? (所以爆炸将起作用)。

必须包含字符串中的撇号,所以不能使用str_getcsv()。

+2

当您在某人已经拥有某个设备之后更改需求时,很难正确回答您的问题发怒;-) – Roman

回答

1

这里是我的方式:

$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); 

输出:

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 
) 

或者,这可能是更合适的,但你失去了报价,我想,如果你输入的字符串不尊重所有CSV标准,你可能会产生边界效应,因为str_getcsv处理的事情超过此引用问题:

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

您可以手动做到这一点和改进,以支持更多的情况下...尝试这样的事情:

$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]; 
    } 
} 

结果:

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

注意:它会保持“空”周围的空间昏迷

1

尝试使用str_getcsv

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