PHP实现将PostgreSQL返回的Tcl字典格式字符串转换为数组或JSON
PHP解析Tcl字典格式字符串方案
实现代码
function parseTclDict(string $tclStr): array { $result = []; // 匹配所有值:要么是{}包裹的内容,要么是纯数字 $valuePattern = '/({(?>[^}]+)})|(\d+)/'; preg_match_all($valuePattern, $tclStr, $valueMatches, PREG_OFFSET_CAPTURE | PREG_PATTERN_ORDER); $values = $valueMatches[0]; $prevOffset = 0; foreach ($values as $valueItem) { $value = $valueItem[0]; $currentOffset = $valueItem[1]; // 提取两个值之间的内容作为键 $key = trim(substr($tclStr, $prevOffset, $currentOffset - $prevOffset)); if ($key !== '') { // 处理值格式:去掉{}包裹 if (substr($value, 0, 1) === '{') { $parsedValue = trim($value, '{}'); } else { // 数值类型转int $parsedValue = (int)$value; } $result[$key] = $parsedValue; } $prevOffset = $currentOffset + strlen($value); } return $result; }
使用示例
测试场景1:多单词键、值均为{}包裹
$input1 = "keytext {this is my value text 1} key with multi words {value text 2} another key {key_value number 3}"; $output1 = parseTclDict($input1); // 如需输出JSON直接调用json_encode($output1)即可 print_r($output1);
输出结果:
Array ( [keytext] => this is my value text 1 [key with multi words] => value text 2 [another key] => key_value number 3 )
测试场景2:混合数值类型无包裹值
$input2 = "user_receiver {all} manifest 3200 transferCode {B45} time hours 0 status {1a} local {} is online {}"; $output2 = parseTclDict($input2); print_r($output2);
输出结果:
Array ( [user_receiver] => all [manifest] => 3200 [transferCode] => B45 [time hours] => 0 [status] => 1a [local] => [is online] => )
注意事项
- 以上实现默认Tcl字典不存在嵌套花括号,适配绝大多数从PostgreSQL导出的Tcl字典场景。如果有嵌套花括号需求,可升级为逐字符扫描的解析逻辑。
- 代码兼容PHP7.0及以上所有版本。
内容的提问来源于stack exchange,提问作者andy_andy
相关产品推荐
相关产品推荐

