【问题标题】:splitting string into an array unless comma between speech marks除非语音标记之间有逗号,否则将字符串拆分为数组
【发布时间】:2012-10-01 22:25:34
【问题描述】:

我正在编写一个 csv 文件重要脚本。有两种分隔符可供选择,逗号或分号。我注意到虽然在文本文件中,一些文本的中间有分号和逗号。每个文本字段周围都有语音标记,但有些字段是空白的,有些是数字的。我正在寻找一种方法来仅拆分语音标记之外的文本,同时保留文本而不是语音标记。

这是我用来分割行的当前函数。

function parse_lines($p_CSVLines,$c_Names,$separator)
{
    $content = FALSE;
    if( !is_array($content) ) { // the first line contains fields numbers
        $this->fields = $c_Names;
        $content = array();
    }

    foreach($p_CSVLines as $line_num => $line){
        if($line != ''){ // skip empty lines
            $elements = split($separator, $line);
            $item = array();
            foreach($this->fields as $id => $field){
                if( isset($elements[$id]) ){
                   $field = trim($field,"\"");
                   $item[$field] = trim($elements[$id],"\"");
                }
            }
            $content[] = $item;
        }
    }
    return $content;
}

【问题讨论】:

标签: php csv import


【解决方案1】:

请注意,强烈建议不要使用split(),它现在已被弃用。您可以使用preg_split()explode()

您在这里要做的是使用 REGEX 搜索不在文本中间的分号和逗号。 preg_split() 应该用正确的表达方式完成工作。

http://ca3.php.net/manual/en/function.preg-split.php

【讨论】:

    猜你喜欢
    • 2021-02-24
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-15
    • 2015-04-24
    • 1970-01-01
    相关资源
    最近更新 更多