Php 将(非标准)json解析为数组/对象
我有这样的字符串:Php 将(非标准)json解析为数组/对象,php,json,string-parsing,Php,Json,String Parsing,我有这样的字符串: ['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', ]; 我想把它
['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',
];
我想把它转换成这样的数组:
['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',
];
我如何解析它?
任何提示或代码将不胜感激
什么是做不到的?
- 使用标准json解析器
- eval()
- explode()按
和explode()按,
:
<?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;
}
不幸的是,字符串不是json。在上面的例子中[3:$var]中有不带引号的字符串。如果你试图用代码编写一些东西,你会从社区得到更好的响应。否则看起来你是在问DIFMquestion@tempoman在您的问题中,您在输入数组的索引3处指定了:3:$var。这是一个打字错误吗?它实际上是3:“$var”吗?我的意思是,$var是从一个PHP变量中取值的,或者是“字面上”的“$var”?按拆分字符串,
分隔符和循环数组,循环中按拆分每个项目的内容:
分隔符并将值存储在新数组中。@Maurizio不,它不是一种类型,$var是一个字符串值,可以是任何有效的PHP变量(如$arr['hello'][…]否则它也是一个有效的json。