All pastes #918837 Raw Edit

parseCSV

public php v1 · immutable
#918837 ·published 2008-02-26 12:02 UTC
rendered paste body
/* Takes string converts to 2d array and returns known values - html (26/02/08)*/function parseCSV($csv) {    // convert string to array by newline    $csv = explode("\n", $csv);    // now that we have the array we need to split based on ,    $csvn = array();    foreach ($csv as $c) {        // remove any dud lines        if (!preg_match('/^\b+$/', $c) && $c != '') {            $temp = explode(",", $c);            $count = sizeof($temp); $empty =0;            $wrong = false;            for($i=0;$i<=$count;$i++) {                $nquotes = substr_count($temp[$i], '"');                if ($nquotes %2 == 1) {                    for ($j = $i+1; $j < count($temp); $j++) {                        if (substr_count($temp[$j], '"') > 0) {                            // Put the quoted string's pieces back together again                            array_splice($temp, $i, $j-$i+1,                                implode($separator, array_slice($temp, $i, $j-$i+1)));                            break;                        }                    }                }                if ($nquotes > 0) {                    // Remove first and last quotes, then merge pairs of quotes                    $qstr =& $temp[$i];                    $qstr = substr_replace($qstr, '', strpos($qstr, '"'), 1);                    $qstr = substr_replace($qstr, '', strrpos($qstr, '"'), 1);                    $qstr = str_replace('""', '"', $qstr);                }                if ($temp[$i] == '' || preg_match('/^\b+$/', $temp[$i])) {                    $empty++;                }                if ($empty >= $count/2 || stristr($temp[$i],'Merchandiser') || stristr($temp[$i], '"Cash and Carry') || stristr($temp[$i], 'Motorway Service Areas') || stristr($temp[$i],'"Forecourts')) { $wrong = true; }            }            if ($wrong == false) $csvn[] = explode(",", $c);        }    }        // now that we have our array we need to name the fields    return $csvn;}