0

How do I explode the following string:

$str = "ProductId=123, Name=Ancient Roots, Modern Pursuits, Country=India, City=Bangalore, Price=3368"

Such that the output array will contain:

[
    "ProductId" => "123",
    "Name" => "Ancient Roots, Modern Pursuits",
    "Country" => "India",
    "City" => "Bangalore",
    "Price" => "3368" 
]

I tried to explode by "comma", then each element again explode by "equal to" as.

$arr = explode(",", $str);

and again

$prodarr = explode("=", $arr[0]);  
$product["ProductId"] = $prodarr[1]

But I'm facing the problem when another comma exists in a value like in name Ancient Roots, Modern Pursuits.

5
  • Can you control how this string is created? Commented May 29, 2018 at 11:39
  • Is there a safe rule to follow? E.g. that the word before = is always a single word without commas or spaces? Also, if you have control over it, can't you simply switch to an established format like JSON? Commented May 29, 2018 at 11:40
  • No, its a response from rest api Commented May 29, 2018 at 11:40
  • 2
    As a comma can mean multiple things, don't think you'd be able to do this with explode alone. You'd be able to accomplish it with a regular expression with a lookahead... until the next weird data format hit you. It would be much easier if you could get it in a better data format, either the current format with a delimiter or a standardised format like JSON Commented May 29, 2018 at 11:41
  • @Bharat You should contact the support team for this API. It is not built well, the values should be encapsulated. Commented May 29, 2018 at 12:06

3 Answers 3

4

Your structure is very weak for breaking. But you can still try to parse it.

First explode on =. You will have next key and current value.

Then loop these and explode on , and select last element for next key and all previous parts as value (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));
Sign up to request clarification or add additional context in comments.

Comments

1

I played a little bit around. I used preg_match_all() to extract the Patterns which contain characters that are no , and no = followed by a = followed by characters that are no = followed by a , or end of line. here is the result:

$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);

The result is:

{"ProductId":"123","Name":"Ancient Roots, Modern Pursuits","Country":"India","City":"Bangalore"}

Comments

0

Try something like this

<?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);
?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.