Created
April 29, 2018 10:50
-
-
Save matrey/0075513ba5525eecea794e219719afbb to your computer and use it in GitHub Desktop.
Linear TSV encode/decode for PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function ltsv_decode($data){ | |
// From parse_field (https://github.com/solidsnack/tsv/blob/master/tsv.py#L90) | |
$stack = []; | |
$replaces = ['t' => "\t", 'n' => "\n", 'r' => "\r", '\\' => "\\"]; | |
$tmp = explode("\\", $data, 2); | |
while (count($tmp) >= 2){ | |
$stack[] = $tmp[0]; | |
$next = substr($tmp[1], 0, 1); | |
if (isset($replaces[$next])){ | |
$stack[] = $replaces[$next]; | |
$tmp = explode("\\", substr($tmp[1], 1), 2); | |
}else{ | |
$tmp = explode("\\", $tmp[1], 2); | |
} | |
} | |
$stack[] = $tmp[0]; | |
return implode('', $stack); | |
} | |
function ltsv_encode($data){ | |
// From format_field (https://github.com/solidsnack/tsv/blob/master/tsv.py#L138) | |
return str_replace(["\\","\n","\t","\r"],["\\\\", "\\n","\\t","\\r"], $data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reference implementation in Python at https://github.com/solidsnack/tsv
Spec at http://specs.okfnlabs.org/linear-tsv/
Does:
\n
for newline,\t
for tab,\r
for carriage return,\\
for backslash.Does not do: