用不用引号引起来的分号分隔 [英] Splitting by a semicolon not surrounded by quote signs
问题描述
社区,你好.我正在使用PHP的CSV解码器进行工作(是的,我知道已经有一个,但是对我来说是个挑战,因为我在业余时间学习它).现在的问题是:好吧,这些行被PHP_EOL
拆分了.
Well, hello community. I'm workin' on a CSV decoder in PHP (yeah, I know there's already one, but as a challenge for me, since I'm learning it in my free time). Now the problem: Well, the rows are split up by PHP_EOL
.
在这一行:
foreach(explode($sep, $str) as $line) {
其中 sep 是用于拆分行的变量,而 str 是我想要解码的字符串.
where sep is the variable which splits up the rows and str the string I wanna decode.
但是,如果我想用分号将各列分开,则可能会出现分号属于一列的情况.正如我研究的那样,这个问题可以通过用诸如此类的引号将整个列括起来来解决:
But if I wanna split up the columns by a semicolon there might be a situation where a semicolon is content of one column. And as I researched this problem is solved by surrounding the whole column by quote signs like this:
输入:
"0;0";1;2;3;4
预期输出:
0; 0 | 1 | 2 | 3 | 4
0;0 | 1 | 2 | 3 | 4
我已经想到了向前/向后看.但是由于我过去没有使用过,也许这可能是个好习惯,因为我不知道如何将其包含在正则表达式中.我的解码函数返回一个2D数组(如表...),我想到了要像这样向该数组添加行(是的,正则表达式已经搞定了……):
I already thought of lookahead/lookbehind. But as I didn't use it in past and maybe this could be a good practice for it I don't know how to include it in the regex. My decoding function returns a 2D-array (like a table...) and I thought of adding rows to the array like this (Yep, the regex is f***ed up...):
$res[] = preg_split("/(?<!\")". preg_quote($delim). "(?!\")/", $line);
最后是我的完整代码:
function csv_decode($str, $delim = ";", $sep = PHP_EOL) {
if($delim == "\"") $delim = ";";
$res = [];
foreach(explode($sep, $str) as $line) {
$res[] = preg_split("/(?<!\")". preg_quote($delim). "(?!\")/", $line);
}
return $res;
}
提前谢谢!
推荐答案
您可以使用此功能str_getcsv
,也可以指定自定义分隔符(;
).
You can use this function str_getcsv
in this you can specify a custom delimiter(;
) as well.
<?php
$string='"0;0";1;2;3;4';
print_r(str_getcsv($string,";"));
输出:
Array
(
[0] => 0;0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
)
这篇关于用不用引号引起来的分号分隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!