forked from openemr/openemr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv_like_join.php
107 lines (85 loc) · 2.25 KB
/
csv_like_join.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
function csv_like_join($array, $quote_all = false)
{
$result = '';
$first = true;
foreach ($array as $value) {
if ($first) {
$first = false;
} else {
$result .= ',';
}
if ($quote_all) {
$result .= csv_quote($value);
} else {
$result .= maybe_csv_quote($value);
}
}
return $result;
}
function csv_quote($string)
{
return '"' . str_replace($string, '"', '""') . '"';
}
function maybe_csv_quote($string)
{
if (need_csv_quote($string)) {
return csv_quote($string);
}
return $string;
}
function need_csv_quote($string)
{
if (
strpos($string, ',') === false
&& strpos($string, '"') === false
&& strpos($string, "\r") === false
&& strpos($string, "\n") === false
) {
return false;
}
return true;
}
function split_csv_line($record)
{
$first = null;
if (strlen($record) == 0) {
return array('');
}
if ($record[0] === '"') {
$first = '';
$start = 1;
while (
$start < strlen($record)
&& ($end = strpos($record, '"', $start)) !== false
&& $end < strlen($record) - 1
&& $record[$end + 1] !== ','
) {
if ($record[$end + 1] !== '"') {
die("Found characters between double-quoted field and comma.");
}
$first .= substr($record, $start, $end - $start - 1);
$start = $end + 2;
}
if ($start < strlen($record) || $end === false) {
die("Could not find end-quote for double-quoted field");
}
$first .= substr($record, $start, $end - $start - 1);
if ($end >= strlen($record) - 1) {
return array($first);
}
/* Assertion: $record[$end + 1] == ',' */
$rest = substr($record, $end + 2);
} else {
$end = strpos($record, ',');
if ($end === false) {
return array($record);
}
/* Assertion: $end < strlen($record) */
$first = substr($record, 0, $end);
$rest = substr($record, $end + 1);
}
$fields = split_csv_line($rest);
array_unshift($fields, $first);
return $fields;
}