简体   繁体   中英

php split string with repeated delimiter

How do I split the following string which is seperated by the ',' delimiter to an array in PHP?

String:

[{"sku":"PAP","name":"Butter","price":23,"quantity":2},{"sku":"PER","name":"Garlic","price":25,"quantity":1}]

Required Array:

$array[0]= "sku":"PAP","name":"Butter","price":23,"quantity":2

$array[1]= "sku":"PER","name":"Garlic","price":25,"quantity":1

I am not able to split based on the delimiter',' since it is present in the array elements.

@Ruslan Osmanov is right. Just decode like JSON.

<?php
  $a='[{"sku":"PAP","name":"Butter","price":23,"quantity":2},{"sku":"PER","name":"Garlic","price":25,"quantity":1}]';
  print_r(json_decode($a));
?>

Result:

Array
(
    [0] => stdClass Object
        (
            [sku] => PAP
            [name] => Butter
            [price] => 23
            [quantity] => 2
        )

    [1] => stdClass Object
        (
            [sku] => PER
            [name] => Garlic
            [price] => 25
            [quantity] => 1
        )

)

First, remove the unwanted characters:

$str=str_replace("[{","",$str);
$str=str_replace("}]","",$str);

Then, split with:

$array=preg_split("},{",$str);

字符串在JSON中看起来像,所以请使用php的json_decode()方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM