Last active
December 12, 2015 06:58
-
-
Save katzchang/4733041 to your computer and use it in GitHub Desktop.
PHP配列をS式へ変換する
This file contains hidden or 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 | |
/* | |
* $ 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