Skip to content

Instantly share code, notes, and snippets.

@katzchang
Last active December 12, 2015 06:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save katzchang/4733041 to your computer and use it in GitHub Desktop.
Save katzchang/4733041 to your computer and use it in GitHub Desktop.
PHP配列をS式へ変換する
<?php
/*
* $ php sexp_encode.php | gosh -E"begin (write (read)) (write (read))" -E"exit"
*/
// TODO: symbolエスケープ?
function sexp_str_escape($str) {
return addcslashes($str, "\"\\\n\r\f\t\0");
}
function is_vector($hash) {
$i = 0;
foreach ($hash as $key => $val) {
if (!is_int($key)) return false;
if (!$i === (int)$key) return false;
$i++;
}
return true;
}
function sexp_encode($v, $sdelim="\t", $pdelim = "\t") {
if (is_string($v)) {
return '"'.sexp_str_escape($v).'"';
} else if (is_array($v)) {
$s = '';
if (is_vector($v)) {
foreach ($v as $key => $val) {
$s = $s . sexp_encode($val) . $sdelim;
}
$s = rtrim($s) . $pdelim;
} else {
foreach ($v as $key => $val) {
$s = $s . "($pdelim|".$key."|$sdelim".sexp_encode($val)."$pdelim)$pdelim";
}
}
return "($pdelim$s)";
} else {
return $v;
}
return '';
}
$hoge = array(1,2,3);
$fuga = array();
$fuga['foo'] = 'bar';
$fuga[')('] = 'x x
x';
$fuga['boo'] = ')(babaa"';
$fuga['hoge'] = $hoge;
//echo sexp_encode($fuga);
echo sexp_encode(array("a","b","c"), " ", "");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment