PHP 8.5.0 Alpha 1 available for testing

Voting

: six minus two?
(Example: nine)

The Note You're Voting On

txxllm at hotmail dot com
4 years ago
Sometimes the enclosure parameter of the str_getcsv function doesn't work, so I wrote a function that is equivalent to the function

<?php
/**
* @param string $input
* @param string $delimiter
* @param string $enclosure
* @param string $escape
* @return array
* @author TXX
* @date 2021/1/25 15:03
*/
function my_str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\') {
$output = array();

if (empty(
$input) || !is_string($input)) {
return
$output;
}

if (
preg_match("/". $escape . $enclosure ."/", $input)) {
while (
$strlen = strlen($input)) {
$pos_delimiter = strpos($input, $delimiter); //分隔符出现位置
$pos_enclosure_start = strpos($input, $enclosure); //封闭符-开始出现位置

//有封闭符并封闭符在分隔符之前
if (is_int($pos_delimiter) && is_int($pos_enclosure_start) && $pos_enclosure_start < $pos_delimiter) {
$pos_enclosure_start += 1;
$enclosed_str = substr($input, $pos_enclosure_start); //封闭字符串-开始
$pos_enclosure_end = strpos($enclosed_str, $enclosure); //封闭符-结尾封闭字符串-开始中出现位置
$pos_enclosure_end += $pos_enclosure_start; //封闭符-结尾在原始数据中出现位置

if ($pos_enclosure_end < $pos_delimiter) {
//封闭符-结束在分隔符之前,无需进行封闭
$output[] = substr($input, 0, $pos_delimiter);
$offset = $pos_delimiter + 1;
} else {
//封闭符-结束在分隔符之后,需要封闭
$pos_enclosure_end += 1;
$before_enclosed_str = substr($input, 0, $pos_enclosure_end);
$enclosed_str = substr($input, $pos_enclosure_end); //封闭字符串之后的字符串

$enclosed_arr = my_str_getcsv($enclosed_str, $delimiter, $enclosure); //将封闭之后的字符串执行自身
$enclosed_arr[0] = $before_enclosed_str . $enclosed_arr[0];

$output = array_merge($output, $enclosed_arr);
$offset = strlen($input); //光标移至结尾
}
} else {
//无封闭
if (!is_int($pos_delimiter)) {
//无分隔符,直接将字符串加入输出数组
$output[] = $input;
//光标移至结尾
$offset = strlen($input);
} else if (
$input == $delimiter) {
//如果字符串只剩下分隔符,需保存'',''
$output = array_merge($output, ['','']);
$offset = $pos_delimiter+1; //光标移至分隔符后一位
} else {
$output[] = substr($input, 0, $pos_delimiter); //将分割符之前的数据
$offset = $pos_delimiter+1; //光标移至分隔符后一位
}
}
//将字符串更新至光标位置
$input = substr($input,$offset);
}
} else {
//字符串中不存在封闭符,直接通过分隔符分割
$input = preg_split("/". $escape . $delimiter ."/", $input);

if (
is_array($input)) {
$output = $input;
}
}

return
$output;
}

?>

<< Back to user notes page

To Top