繁体   English   中英

PHP:使用preg_match_all将csv拆分为可用数组

[英]PHP: Using preg_match_all to split csv into usable array

我试图在php中使用preg_match_all来拉出csv字符串的各个部分。

这是我目前正在尝试的代码:

$csv = "1,2,3,4";
$match = "/^(\d+)(?:,(\d+))*$/";

$matches = array();

preg_match_all($match, $csv, $matches);

print_r($matches);

我期望的是:

Array
(
    [0] => Array
        (
            [0] => 1,2,3,4
        )
    [1] => Array
        (
            [0] => 1
        )
    [2] => Array
        (
            [0] => 2
        )
    [3] => Array
        (
            [0] => 3
        )
    [4] => Array
        (
            [0] => 4
        )
)

我得到的是:

Array
(
    [0] => Array
        (
            [0] => 1,2,3,4
        )
    [1] => Array
        (
            [0] => 1
        )
    [2] => Array
        (
            [0] => 4
        )
)

我只能修改'^'和'$'之间的内容,因为这只是完整字符串的一部分。

有想法该怎么解决这个吗?

function csvToArray( $csvxrow , $delm = ';' , $encl ='"' , $head = true )
{ 
    $csvxrow[0] = chop( $csvxrow[0] ); 
    $csvxrow[0] = str_replace( $encl, '' ,$csvxrow[0] ); 
    $keydata = explode( $delm, $csvxrow[0] ); 
    $keynumb = count( $keydata ); 

    if ( $head === true )
    { 
    $anzdata = count( $csvxrow ); 
    $z = 0; 
    for( $x = 1; $x < $anzdata; $x++ )
    { 
        $csvxrow[$x] = chop( $csvxrow[$x] ); 
        $csvxrow[$x] = str_replace( $encl, '', $csvxrow[$x] ); 
        $csv_data[$x] = explode( $delm, $csvxrow[$x] ); 
        $i = 0; 
        foreach( $keydata as $key )
        { 
            $out[$z][$key] = $csv_data[$x][$i]; 
            $i++;
        }    
        $z++;
        }
    }
    else
    { 
        $i = 0;
        foreach( $csvxrow as $item )
        { 
            $item = chop( $item ); 
            $item = str_replace( $encl, '', $item ); 
            $csv_data = explode( $delm, $item ); 
            for( $y = 0; $y < $keynumb; $y++ )
            { 
               $out[$i][$y] = $csv_data[$y]; 
            }
        $i++;
        }
    }

    return $out; 
}

这就是我用的。 PHP为此具有特定的功能,但是它们不是很好。

如果CSV中没有列标题,请将head设置为false。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM