srisar
srisar

Reputation: 1571

Parse a string of key=value assignments with no delimiter between expressions

I have a string in PHP like the following

$data = "ID=53KEY=23";

and I want to assign the values from this string to following variables

$id = 53;
$key = 23;

How can I do this in PHP?

Upvotes: -2

Views: 114

Answers (4)

mickmackusa
mickmackusa

Reputation: 47874

Predictably formatted strings with no optional expressions can be parsed with sscanf() and numeric values can be explicitly cast as numeric types. In this case, use % to cast numbers as int type values.

Code: (Demo)

$data = "ID=53KEY=23";
sscanf($data, 'ID=%dKEY=%d', $id, $key);
var_dump($id, $key);

Output:

int(53)
int(23)

Upvotes: 0

The Mask
The Mask

Reputation: 17427

Try this:

$data = "ID=53KEY=23"; 

preg_match("/id=(?<id>\d+)&?key=(?<key>\d+)/i",$data,$array); 
$id = $array["id"]; // 53
$key = $array["key"]; //23
print("id = $id, key = $key\n");

Upvotes: 2

Bryan Alves
Bryan Alves

Reputation: 619

This function will work for more generic key/value inputs, not just ID/KEY

$input = "ID=53KEY=23";

$res = preg_split("/([[:upper:]]+)=([[:digit:]]+)/", $input, null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
for ($i = 0 ; $i < count($res) ; $i += 2)
{
    $res[$i] = strtolower($res[$i]);
    $$res[$i] = $res[$i+1];
}

//$id = 53
//$key = 23

Upvotes: 3

moteutsch
moteutsch

Reputation: 3831

For a more generic solution:

$data = "ID=53KEY=23AGE=318";
$array = array();
if(preg_match_all("/([A-Z]+)=(\d+)/", $data, $matches)) {
    $array = array_change_key_case(array_combine($matches[1], $matches[2]));
}

echo "ID: " . $array['id'] . ", KEY: " . $array['key'] . ", AGE: " . $array['age'];

Upvotes: 2

Related Questions