php源码之解析CSV字符串

时间:2016-08-04
本文章向大家介绍php如何解析CSV字符串,该源码主要使用到php字符串替换函数和正则匹配函数,需要的朋友可以参考一下本文章的源代码。

php解析CSV字符串,源码如下:

<?php
function parse_csv($string, $delim = ',', $quote='"') {
    $new = str_replace("{$quote}{$quote}", $quote, $string);

    $matches = array();
    preg_match_all("/\s*({$quote}?)(.*?)\\1\s*(?:{$delim}|$)/",
        $new, $matches);

    array_pop($matches[2]);
    return $matches[2];
}
/* http://www.manongjc.com/article/1309.html */
$str = 'c "s""v""","s", "f\ny" ';

$values = parse_csv($str);

echo '<pre>';
print_r($values);
echo '</pre>';
?>