Jerome
Jerome

Reputation: 11

Parse colon delimited string into variables based on a value's preceding label

We are trying to get certain parts of a string.

We have the string:

location:32:DaD+LoC:102AD:Ammount:294

We would like to put the information in different strings. For example $location=32 and $Dad+Loc=102AD

The values vary per string, but it will always have this construction: location:{number}:DaD+LoC:{code}:Ammount:{number}

How do we get those values?

Upvotes: 0

Views: 949

Answers (7)

mickmackusa
mickmackusa

Reputation: 47894

Parsing a predictably formatted string AND casting numeric values as non-string data types can be directly achieved with sscanf(). Demo

$str = 'location:32:DaD+LoC:102AD:Amount:294';
sscanf(
    $str,
    'location:%d:DaD+LoC:%[^:]:Amount:%d',
    $location,
    $dadloc,
    $amount
);
var_dump($location, $dadloc, $amount);

Output:

int(32)
string(5) "102AD"
int(294)

Upvotes: 0

Davincho
Davincho

Reputation: 121

the php function split is deprecated so instead of this it is recommended to use preg_split or explode. very useful in this case is the function list():

list($location, $Dad_Loc, $ammount) = explode(':', $string);

EDIT: my code has an error:

list(,$location,, $Dad_Loc,, $ammount) = explode(':', $string);

Upvotes: 0

Your Common Sense
Your Common Sense

Reputation: 157864

it seems nobody can do it properly

$string = "location:32:DaD+LoC:102AD:Ammount:294";
list(,$location,, $dadloc,,$amount) = explode(':', $string);

Upvotes: 0

thomasmalt
thomasmalt

Reputation: 1752

By using preg_split and mapping the resulting array into an associative one. Like this:

$str  = 'location:32:DaD+LoC:102AD:Ammount:294';
$list = preg_split('/:/', $str);

$result = array();
for ($i = 0; $i < sizeof($list); $i = $i+2) {
    $result[$array[$i]] = $array[$i+1];
};

print_r($result);

Upvotes: 2

Hannes
Hannes

Reputation: 8237

That would produce what you want, but for example $dad+Loc is an invalid variable name in PHP so it wont work the way you want it, better work with an array or an stdClass Object instead of single variables.

  $string = "location:32:DaD+LoC:102AD:Ammount:294";
  $stringParts = explode(":",$string);
  $variableHolder = array();
  for($i = 0;$i <= count($stringParts);$i = $i+2){
      ${$stringParts[$i]} = $stringParts[$i+1];
  }

  var_dump($location,$DaD+LoC,$Ammount);

Upvotes: 3

Thariama
Thariama

Reputation: 50832

Easy fast forward approach:

$string = "location:32:DaD+LoC:102AD:Ammount:294";

$arr = explode(":",$string);

$location= $arr[1];
$DaD_LoC= $arr[3];
$Ammount= $arr[5];

Upvotes: 2

elsni
elsni

Reputation: 2053

$StringArray = explode ( ":" , $string)

Upvotes: 2

Related Questions