More security stuff.
[openemr.git] / library / csv_like_join.php
blobfce70772697b78b2fe4804e289531513d1042e0f
1 <?php
2 function csv_like_join($array, $quote_all = FALSE) {
3 $result = '';
4 $first = TRUE;
6 foreach ($array as $value) {
7 if ($first) {
8 $first = FALSE;
9 } else {
10 $result .= ',';
12 if ($quote_all) {
13 $result .= csv_quote($value);
14 } else {
15 $result .= maybe_csv_quote($value);
19 return $result;
22 function csv_quote($string) {
23 return '"' . str_replace($string, '"', '""') . '"';
26 function maybe_csv_quote($string) {
27 if (need_csv_quote($string)) {
28 return csv_quote($string);
31 return $string;
34 function need_csv_quote($string) {
35 if (strpos($string, ',') === FALSE
36 && strpos($string, '"') === FALSE
37 && strpos($string, "\r") === FALSE
38 && strpos($string, "\n") === FALSE)
40 return FALSE;
43 return TRUE;
46 function split_csv_line($record) {
47 $first = NULL;
49 if (strlen($record) == 0) {
50 return array('');
53 if ($record[0] === '"') {
54 $first = '';
55 $start = 1;
57 while ($start < strlen($record)
58 && ($end = strpos($record, '"', $start)) !== FALSE
59 && $end < strlen($record) - 1
60 && $record[$end + 1] !== ',')
62 if ($record[$end + 1] !== '"') {
63 die("Found characters between double-quoted field and comma.");
66 $first .= substr($record, $start, $end - $start - 1);
67 $start = $end + 2;
70 if ($start < strlen($record) || $end === FALSE) {
71 die("Could not find end-quote for double-quoted field");
74 $first .= substr($record, $start, $end - $start - 1);
76 if ($end >= strlen($record) - 1) {
77 return array($first);
80 /* Assertion: $record[$end + 1] == ',' */
81 $rest = substr($record, $end + 2);
82 } else {
83 $end = strpos($record, ',');
85 if ($end === FALSE) {
86 return array($record);
89 /* Assertion: $end < strlen($record) */
91 $first = substr($record, 0, $end);
92 $rest = substr($record, $end + 1);
95 $fields = split_csv_line($rest);
96 array_unshift($fields, $first);
97 return $fields;