如何爆炸以下字符串
$ str =" ProductId = 123,Name = Ancient Roots,Modern Pursuits,Country = India,City = Bangalore,Price = 3368"
这样输出数组将包含
[
"ProductId" => "123",
"Name" => "Ancient Roots, Modern Pursuits",
"Country" => "India",
"City" => "Bangalore",
"Price" => "3368"
]
我试图通过"逗号"爆炸,然后每个元素再次被"等于"爆炸。如。
$arr = explode(",", $str);
再次
$prodarr = explode("=", $arr[0]);
$product["ProductId"] = $prodarr[1]
但面对问题,当另一个逗号存在于价值中时,如姓名"古代根源,现代追求"
答案 0 :(得分:4)
你的结构非常弱。但你仍然可以尝试解析它。
首先在=
爆炸。您将拥有下一个键和当前值。
然后循环这些并在,
上爆炸,并选择下一个键的最后一个元素和所有前面的部分作为值(sample):
<?php
$str = "ProductId=123, Name=Ancient Roots, Modern Pursuits, Country=India, City=Bangalore, Price=3368";
$chunks = explode('=', $str);
$keys = [];
$values = [];
foreach ($chunks as $i => $chunk) {
$parts = explode(',', $chunk);
if ($i != count($chunks) - 1) {
$keys[] = trim(array_pop($parts));
}
if ($i != 0) {
$values[] = implode(',', $parts);
}
}
var_dump(array_combine($keys, $values));
答案 1 :(得分:1)
我玩了一下。我使用preg_match_all()来提取包含no的字符的模式,no =后跟a =后跟no =后跟a或行尾的字符。结果如下:
$result = array();
preg_match_all('/([^=,]+=[^=]+)(,|$)/', $string, $matches);
foreach($matches[1] as $data){
$data = explode('=', $data);
$result[trim($data[0])] = trim($data[1]);
}
$result = json_encode($result);
结果是:
{"ProductId":"123","Name":"Ancient Roots, Modern Pursuits","Country":"India","City":"Bangalore"}
答案 2 :(得分:0)
尝试这样的事情
<?php
$str = "ProductId=123, Name=Ancient Roots, Modern Pursuits, Country=India, City=Bangalore, Price=3368";
$str_arr = explode(",", $str);
$json_array = array();
for ($i = 0; $i < sizeof($str_arr); $i++)
{
if (isset($str_arr[$i + 1]))
{
if (strpos($str_arr[$i + 1], '=') !== false)
{
$prod = explode("=", $str_arr[$i]);
$json_array["" . $prod[0] . ""] = "" . $prod[1] . "";
}
else
{
$textAppend = "," . $str_arr[$i + 1];
$prod = explode("=", $str_arr[$i]);
$json_array["" . $prod[0] . ""] = "" . $prod[1] . "" . $textAppend . "";
$i++;
}
}
else
{
$prod = explode("=", $str_arr[$i]);
$json_array["" . $prod[0] . ""] = "" . $prod[1] . "";
}
}
var_dump($json_array);
?>