From ca8d809d46670a124fed16a14b06505f1ec7a60c Mon Sep 17 00:00:00 2001 From: Urban Müller Date: Mon, 22 May 2017 11:17:40 +0200 Subject: introduce fixcolnames in ::csv --- it_pipe.class | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) (limited to 'it_pipe.class') diff --git a/it_pipe.class b/it_pipe.class index 2ab931b..281ee5f 100644 --- a/it_pipe.class +++ b/it_pipe.class @@ -160,16 +160,18 @@ function cols($collist, $separator = "\t") /** * Return contents of pipe as associative records. Column titles read from first line, separators can be \t or ; or , - * @param $forceschema ignore schema in file, replace it with this comma separated column list + * @param $p['forceschema'] ignore schema in file, replace it with this comma separated column list + * @param $p['fixcolnames'] replace non-identifier chars in colum names */ -function csv($forceschema = null) +function csv($p = []) { + $p = is_string($p) ? ['forceschema' => $p] : $p; $counts = count_chars($this->lines[0]); $splitchar = $counts[ord("\t")] ? "\t" : ($counts[ord(";")] > $counts[ord(",")] ? ";" : ","); $csvhead = array_shift($this->lines); - $cols = $forceschema ? explode(",", $forceschema) : str_getcsv(trim($csvhead, "#\n "), $splitchar, '"'); # should function_exists('str_getcsv') - foreach (preg_grep('/^$/', $cols) as $idx => $dummy) - $cols[$idx] = "field$idx"; # replace empty column names + $cols = $p['forceschema'] ? explode(",", $p['forceschema']) : str_getcsv(trim($csvhead, "#\n "), $splitchar, '"'); # should function_exists('str_getcsv') + foreach ($cols as $idx => $col) + $cols[$idx] = it::replace(['^$' => "field$idx", '\W' => $p['fixcolnames'] ? "_" : '$0'], $col); $oldlocale = setlocale(LC_CTYPE, "0"); setlocale(LC_CTYPE, 'de_CH.iso-8859-1'); # this works for utf-8 as well -- cgit v1.2.3