I'm trying to build a recursive function in PHP that takes a string with nested {} values and converts it into an nested array. Is there any built in functions that can simply split this?
Also the { brackets will always be on the same line as the key i.e. (Main{) not Main\n{.
Indentation will also always be consistent.
Example of what I'm looking for below.
Main{
NetworkAccess 1;
MaxCPE 6;
MaxClassifiers 20;
GlobalPrivacyEnable 1;
BaselinePrivacy{
AuthTimeout 10;
ReAuthTimeout 10;
AuthGraceTime 600;
OperTimeout 10;
ReKeyTimeout 10;
TEKGraceTime 600;
AuthRejectTimeout 60;
SAMapWaitTimeout 1;
SAMapMaxRetries 4;
}
UsServiceFlow{
UsServiceFlowRef 1;
QosParamSetType 7;
TrafficPriority 2;
MaxRateSustained 1000000;
SchedulingType 2;
MaxTrafficBurst 8000;
MaxConcatenatedBurst 8000;
}
DsServiceFlow{
DsServiceFlowRef 101;
QosParamSetType 7;
TrafficPriority 2;
MaxRateSustained 10000000;
}
}
Desired result:
Array
(
[Main] => Array
(
[NetworkAccess] => 1
[MaxCPE] => 6
[MaxClassifiers] => 20
[GlobalPrivacyEnable] => 1
[BaselinePrivacy] => Array
(
[AuthTimeout] => 10
[ReAuthTimeout] => 10
[AuthGraceTime] => 600
[OperTimeout] => 10
[ReKeyTimeout] => 10
[TEKGraceTime] => 600
[AuthRejectTimeout] => 60
[SAMapWaitTimeout] => 1
[SAMapMaxRetries] => 4
)
[UsServiceFlow] => Array
(
[UsServiceFlowRef] => 1
[QosParamSetType] => 7
[TrafficPriority] => 2
[MaxRateSustained] => 1000000
[SchedulingType] => 2
[MaxTrafficBurst] => 8000
[MaxConcatenatedBurst] => 8000
)
[DsServiceFlow] => Array
(
[DsServiceFlowRef] => 101
[QosParamSetType] => 7
[TrafficPriority] => 2
[MaxRateSustained] => 10000000
)
)
)
JSON would be better, but it was going to be more difficult as it doesn't like trailing commas where they are not needed (PHP doesn't mind).
$string = "[".str_replace(['{', '}', ';'], ['[', '],', ','], $string)."]";
$string = preg_replace('/([a-z]+)/i', '"$1" =>', $string);
eval("\$result = $string;");
print_r($result);