I have this script to format var_export's result string. The information in the output is good, but I need know if the code performance is good or if it can be improved.
https://wtools.io/php-sandbox/biDk
<?php
#Variable:
$Test = [];
$Test['Check1'] = null;
$Test['Check2'] = [];
$Test['Check2']['int'] = 20;
$Test['Check2']['float'] = 20.35;
$Test['Check2']['string'] = 'Hello World';
$Test['Check2']['bolean'] = true;
$Test['Check2']['array'] = [];
$Test['Check2']['array']['data'] = 'Array Text';
class Example {
function foo_function() {
return "Hello World! Object";
}
}
$var_object = new Example;
$Test['Check2']['array']['object'] = $var_object;
$Test['Check2']['array']['object2'] = $var_object->foo_function();
#Script Type:
function myGetType($var) {
if (is_null($var) OR $var == 'null' OR $var == 'NULL') {
return "(NULL)";
}
if (is_array($var)) {
return "array";
}
if (in_array($var, array("true", "false"), true)) {
return "boolean";
}
if ((int) $var == $var && is_numeric($var)) {
return "integer" . '(' . strlen($var) . ')';
}
if ((float) $var == $var && is_numeric($var)) {
return "float" . '(' . strlen($var) . ')';
}
if (is_object($var)) {
return "object";
}
if (is_resource($var)) {
return "resource";
}
if (is_string($var)) {
return "string" . '(' . strlen($var) . ')';
}
return "unknown";
}
#Script Analisis:
function VarExportFormat($Var) {
$textvar = '';
$textvar = var_export($Var, true);
$textvar = preg_replace("/^([ ]*)(.*)/m", '$1$1$2', $textvar);
$textvarArr = preg_split("/\r\n|\n|\r/", $textvar);
# Analisis del tipo.
foreach ($textvarArr as $key => $value) {
preg_match('~=>\\s(.*?),~', $value, $newvalue);
if (!empty($newvalue)) {
$newvalue[1] = str_replace("'", "", $newvalue[1]);
$typeval = myGetType($newvalue[1]);
$value = str_replace("=> ", "=> " . $typeval . ': ', $value);
$textvarArr[$key] = $value;
}
}
$textvarArr = preg_replace(["/\s*array\s\($/", "/\)(,)?$/", "/\s=>\s$/"], [NULL, ']$1', ' => array ['], $textvarArr);
$textvar = join(PHP_EOL, array_filter(["array ["] + $textvarArr));
if (substr($textvar, -1) == '[') {
$textvar = str_replace("[", "[]", $textvar);
}
$textvar = str_replace("__set_state", "__set_state(object)", $textvar);
$textvar = highlight_string("<?php \n#output of Variable:\n" . $textvar . ";\n?>", true);
return $textvar;
}
echo VarExportFormat($Test);
(string)$string == $stringcan be a replacement aswell foris_string(), same trick you did with int and floats.. \$\endgroup\$(object)$var == $varand(array)$var == $varcan also works aswell to replace is_object and is_array but performance is more depending on the object or array size and or PHP version, this trick does not scale that that well as the int, string types.. Might be interesting to test with? \$\endgroup\$var_export()returns parseable PHP... \$\endgroup\$