隐藏字符串到JSON对象

Zileia

我有一串

$string = "\nManufacturer\n\n\n\n\n\n\n\nYves Saint Laurent\n\n\n\nItem Package Dimensions L x W x H\n\n\n\n\n\n\n\n11.9 x 7.4 x 7.1 centimetres\n\n\n\nPackage Weight\n\n\n\n\n\n\n\n0.23 Kilograms\n\n\n\nItem Dimensions L x W x H\n\n\n\n\n\n\n\n5.1 x 5.1 x 15.2 centimetres\n\n\n\nItem Weight\n\n\n\n\n\n\n\n0.12 Kilograms\n\n\n\nBrand\n\n\n\n\n\n\n\nYSL\n\n\n\nFormat\n\n\n\n\n\n\n\nSpray\n\n\n\nVolume\n\n\n\n\n\n\n\n125 Millilitres\n\n\n\nScent\n\n\n\n\n\n\n\nChypre, Floral\n\n\n\nPet Type\n\n\n\n\n\n\n\nWomen\n\n\n\nItem model number\n\n\n\n\n\n\n\n123751\n\n\n\nProduct Dimensions\n\n\n\n\n\n\n\n5.08 x 5.08 x 15.24 cm; 120 Grams\n\n\n\nASIN\n\n\n\n\n\n\n\nB000C1W70S\n\n\n";

我想将其转换为json对象,就像

{
    "detail": {
        "Manufacturer":"Yves Saint Laurent",
        "Item Package Dimensions L x W x H":"11.9 x 7.4 x 7.1 centimetres",
        "Package Weight":"0.23 Kilograms",
        "Item Dimensions L x W x H":"5.1 x 5.1 x 15.2 centimetres",
        "Item Weight":"0.12 Kilograms",
        "Brand":"YSL",
        "Format":"Spray",
        "Volume":"125 Millilitres",
        "Scent":"Chypre, Floral",
        "Pet Type":"Women",
        "Item model number":"123751",
        "Product Dimensions":"5.08 x 5.08 x 15.24 cm; 120 Grams",
        "ASIN":"B000C1W70S"
    }
}

到目前为止,我已经尝试过了:

$str = str_replace("\n\n\n\n\n\n\n\n",':',$string);
$json->detail = str_replace('\"','"',str_replace("\n","",(explode("\n\n\n\n",$str))));

但是它返回一个数组,所以如果某些细节丢失在字符串中或顺序错误,我将很难从json解析内容。

Nigel Ren

这首先用定界符(在本例中为“ |”)替换所有多个空格字符,然后在此定界符上爆炸以拆分出所有字段。

然后它将替代值组合为键/值(使用循环,您需要将循环分为2个块​​)...

$string = preg_replace('!\s{2,}!', '|', trim($string));
$split = explode("|", $string);
$output = [];
for ( $i = 0; $i < count($split); $i+= 2)   {
    $output [$split[$i]] = $split[$i + 1];
}
print_r($output);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章