我有这样的字符串:
['key1':'value1', 2:'value2', 3:$var, 4:'with\' quotes', 5:'with, comma']
我想将其转换为这样的数组:
$parsed = [
'key1' => 'value1',
2 => 'value2',
3 => '$var',
4 => 'with\' quotes',
5 => 'with, comma',
];
我该如何解析? 任何提示或代码将不胜感激。
不能做什么?
,
和explode()由:
答案 0 :(得分:0)
由于您无法使用任何预构建函数(例如json_decode),因此必须尝试找到最可能的报价方案,并用已知的子字符串替换它们。
鉴于输入数组中所有所有值和/或键都用单引号引起来
请注意:此代码未经测试
<?php
$input = "[ 'key1':'value1', 2:'value2', 3:$var, 4:'with\' quotes', 5: '$var', 'another_key': 'something not usual, like \'this\'' ]";
function extractKeysAndValuesFromNonStandardKeyValueString ( $string ) {
$input = str_replace ( Array ( "\\\'", "\'" ), Array ( "[DOUBLE_QUOTE]", "[QUOTE]" ), $string );
$input_clone = $input;
$return_array = Array ();
if ( preg_match_all ( '/\'?([^\':]+)\'?\s*\:\s*\'([^\']+)\'\s*,?\s*/', $input, $matches ) ) {
foreach ( $matches[0] as $i => $full_match ) {
$key = $matches[1][$i];
$value = $matches[2][$i];
if ( isset ( ${$value} ) $value = ${$value};
else $value = str_replace ( Array ( "[DOUBLE_QUOTE]", "[QUOTE]" ), Array ( "\\\'", "\'" ), $value );
$return_array[$key] = $value;
$input_clone = str_replace ( $full_match, '', $input_clone );
}
// process the rest of the string, if anything important is left inside of it
if ( preg_match_all ( '/\'?([^\':]+)\'?\s*\:\s*([^,]+)\s*,?\s*/', $input_clone, $matches ) ) {
foreach ( $matches[0] as $i => $full_match ) {
$key = $matches[1][$i];
$value = $matches[2][$i];
if ( isset ( ${$value} ) $value = ${$value};
$return_array[$key] = $value;
}
}
}
return $return_array;
}
此功能背后的思想是,首先用您可以轻松替换的东西替换非标准字符串中所有可能的引号组合,然后对您的输入执行标准的正则表达式,然后重新构建所有内容以确保重置之前的内容替换的子字符串