Search code examples
phparraysstringexplode

Broke string into vars with variable position


I need to broke a string into some vars but its order is not fixed as the exemple:

$string = "name='John';phone='555-5555';city='oakland';";
$string2 = "city='oakland';phone='555-5555';name='John';";
$string3 = "phone='555-5555';name='John';city='oakland';";

so I need to broke the strings into:

$name
$phone
$city

if the position would be fixed i could use explode and call for the array key that i need like

$brokenString = explode("'",$string);

$name = $brokenString[1];
$phone = $brokenString[3];
$city = $brokenString[5];

however how could I do it with variable position??


Solution

  • One way to do it with sort to make the position same always for all string variables.

    <?php
    $string = "name='John';phone='555-5555';city='oakland';";
    $string2 = "city='oakland';phone='555-5555';name='John';";
    $string3 = "phone='555-5555';name='John';city='oakland';";
    $array = explode(';',$string3);
    sort($array);
    $array = array_filter($array); # remove the empty element
    foreach($array as $value){
        $split = explode('=',$value);
        $result[$split[0]] = $split[1]; 
    }
    extract($result); # extract result as php variables
    echo "\$city = $city; \$name = $name; \$phone = $phone";
    ?>
    

    EDIT: As using extract() is generally not a good idea.You can use simple foreach() instead of extract(),

    foreach($result as $k => $v) {
      $$k = $v;
    }
    

    WORKING DEMO: https://3v4l.org/RB8pT