Convert string into format array without remove coma PHP

Viewed 67

I have string :

$string = "'id_konversi_aktivitas' => 'f4d943e7', 'nim' => '180218038'"

And I will convert to array like this :

$data = array($string);

But the result is like this :

array(1) { [0]=> string(87) "'id_konversi_aktivitas' => 'f4d943e7', 'nim' => '180218038'" }

I want result like this :

array(2) { ["id_konversi_aktivitas"] => "f4d943e7", ["nim"] => "180218038" }
3 Answers

there is no core PHP function to achieve what you are looking for. You can try in the following way.

$string = "'id_konversi_aktivitas' => 'f4d943e7', 'nim' => '180218038'";
$arrayStr = explode(',', $string);
$myArr = [];
foreach ($arrayStr as $arr) {
    $eachArr = explode('=>', $arr);
    $myArr[trim($eachArr[0])] = $eachArr[1];
}
print_r($myArr);

I made a function specifically for this problem, I hope it helps you out.

function stringToArray($string) {
    $output = [];
    $array = explode(",", $string);
    foreach($array as $elem) {
        $item = explode("=>", $elem);
        $newItem = [
            trim(str_replace("'", "", $item[0])) => $item[1]
        ];
        array_push($output, $newItem);
    }
    return $output;
}

Here's how I used it

<?php  
$string = "'id_konversi_aktivitas' => 'f4d943e7', 'nim' => '180218038'";

function stringToArray($string) {

    $output = [];

    $array = explode(",", $string);
    foreach($array as $elem) {
        $item = explode("=>", $elem);
        $newItem = [
            trim(str_replace("'", "", $item[0])) => $item[1]
        ];
        array_push($output, $newItem);
    }
    return $output;
}

$data = stringToArray($string);
print_r($data[0]["id_konversi_aktivitas"]);

// >> 'f4d943e7'

Using regular expressions instead of a simple explode makes parsing a bit safer. preg_match_all returns the result in a form that returns the desired array with array_combine without a loop.

string = "'id_konversi_aktivitas' => 'f4d\'943e7', 'nim' => '180218038'";

preg_match_all("~'(.+?)' *=> *'(.+?)'(,|$)~",$string,$match);

$array = array_combine($match[1],$match[2]);

var_dump($array);

I added a ' to the string from the request for testing purposes.

Demo: https://3v4l.org/6YO8Q

Related