如何将var_export格式化为php5.4数组语法 [英] How to format var_export to php5.4 array syntax
问题描述
关于来自var输出的有效php语法的主题有很多疑问和答案,我正在寻找一种快速而干净的方法来获取var_export
的输出以使用有效的php5.4数组语法./p>
给予
$arr = [
'key' => 'value',
'mushroom' => [
'badger' => 1
]
];
var_export($arr);
输出
array (
'key' => 'value',
'mushroom' =>
array (
'badger' => 1,
),
)
是否有任何快速简便的方法可以使用方括号语法将其输出为定义的数组?
[
'key' => 'value',
'mushroom' => [
'badger' => 1
]
]
使用regex解析是否是一般共识?如果是这样,有没有人遇到过像样的正则表达式?我将使用的数组的值级别内容都是scalar
和array
,没有对象或类.
我也有类似的情况.
function var_export54($var, $indent="") {
switch (gettype($var)) {
case "string":
return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"';
case "array":
$indexed = array_keys($var) === range(0, count($var) - 1);
$r = [];
foreach ($var as $key => $value) {
$r[] = "$indent "
. ($indexed ? "" : var_export54($key) . " => ")
. var_export54($value, "$indent ");
}
return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
case "boolean":
return $var ? "TRUE" : "FALSE";
default:
return var_export($var, TRUE);
}
}
这不是太漂亮,但也许足以满足您的情况.
除指定类型外,任何其他类型均由常规 var_export
处理.因此,对于单引号字符串,只需注释掉string
情况.
There are lots of questions and answers around the subject of valid php syntax from var outputs, what I am looking for is a quick and clean way of getting the output of var_export
to use valid php5.4 array syntax.
Given
$arr = [
'key' => 'value',
'mushroom' => [
'badger' => 1
]
];
var_export($arr);
outputs
array (
'key' => 'value',
'mushroom' =>
array (
'badger' => 1,
),
)
Is there any quick and easy way to have it output the array as defined, using square bracket syntax?
[
'key' => 'value',
'mushroom' => [
'badger' => 1
]
]
Is the general consensus to use regex parsing? If so, has anyone come across a decent regular expression? The value level contents of the arrays I will use will all be scalar
and array
, no objects or classes.
I had something similar laying around.
function var_export54($var, $indent="") {
switch (gettype($var)) {
case "string":
return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"';
case "array":
$indexed = array_keys($var) === range(0, count($var) - 1);
$r = [];
foreach ($var as $key => $value) {
$r[] = "$indent "
. ($indexed ? "" : var_export54($key) . " => ")
. var_export54($value, "$indent ");
}
return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
case "boolean":
return $var ? "TRUE" : "FALSE";
default:
return var_export($var, TRUE);
}
}
It's not overly pretty, but maybe sufficient for your case.
Any but the specified types are handled by the regular var_export
. Thus for single-quoted strings, just comment out the string
case.
这篇关于如何将var_export格式化为php5.4数组语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!