After really long research, no solution was found. So stackoverflow is my last hope.
In PHP I need a parser for data getting from a postgreSQL DB.
The string construct is like:
"keytext {this is my value text 1} key with multi words {value text 2} another key {key_value number 3}"
So we have the key (could consist of several words) and the value in curly braces.
I think, this data type comes from TCL.
How can we convert this string to a JSON-String or an array in PHP 7/8 ??
THANK you VERY MUCH FOR trying to help me!.
CodePudding user response:
Is not a perfect way but it's work.
$string = "keytext {this is my value text 1} key with multi words {value text 2} another key {key_value number 3}";
$results = explode('{', $string);
$newArray = $values = [];
foreach ($results as $result){
if (strpos($result, '}') !== false) {
$values[] = explode('}', $result)[0];
$keys[] = explode('}', $result)[1];
} else {
$keys[] = $result;
}
}
$newArray = [];
foreach ($keys as $index => $key) {
if ($key !== '' && isset($values[$index])){
$newArray[$key] = $values[$index];
}
}
return $newArray;
CodePudding user response:
Check this out
$str = "keytext {this is my value text 1} key with multi words {value text 2} another key {key_value number 3}";
$chars = str_split($str);
$result_arr = [];
$make_arr_key = true;
$make_arr_key_val = false;
$arr_key = '';
$arr_key_val = '';
foreach ($chars as $char) {
if($char == '{') {
$make_arr_key = false;
$arr_key_val = '';
$make_arr_key_val = true;
}
if($char == '}') {
$result_arr[trim($arr_key)] = trim($arr_key_val);
$arr_key = '';
$make_arr_key = true;
$make_arr_key_val = false;
}
if($make_arr_key) {
if($char != '}'){
$arr_key .= $char;
}
}
if($make_arr_key_val) {
if($char != '{') {
$arr_key_val .= $char;
}
}
}
print_r($result_arr);
Output: