內更換逗號我有一個這樣的字符串:部分字符串
'test', 'test', 'test, test', NULL, NULL, NULL, 123456789012, 0, '2017-02-17', FALSE
我想它爆炸成一個陣列。
但是,當部分字符串包含逗號('test,test')時,會發生混亂。
如何將部分字符串中的逗號替換爲其他字符? (所以爆炸將起作用)。
必須包含字符串中的撇號,所以不能使用str_getcsv()。
內更換逗號我有一個這樣的字符串:部分字符串
'test', 'test', 'test, test', NULL, NULL, NULL, 123456789012, 0, '2017-02-17', FALSE
我想它爆炸成一個陣列。
但是,當部分字符串包含逗號('test,test')時,會發生混亂。
如何將部分字符串中的逗號替換爲其他字符? (所以爆炸將起作用)。
必須包含字符串中的撇號,所以不能使用str_getcsv()。
這裏是我的方式:
$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, ",", "'");
您可以手動做到這一點和改進,以支持更多的情況下...嘗試這樣的事情:
$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
)
注意:它會保持「空」周圍的空間昏迷
嘗試使用str_getcsv
str_getcsv($string, ",", "'");
當您在某人已經擁有某個設備之後更改需求時,很難正確回答您的問題發怒;-) – Roman