views:

66

answers:

7

We are trying to get certain parts of a String.

We have the string:

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

And 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}

So... how do we get those values?

+2  A: 

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

elsni
+2  A: 

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];
Thariama
note that split usage will throw an error
Col. Shrapnel
replaced it with 'explode' right after i submitted my answer
Thariama
A: 

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);
Davincho
+2  A: 

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);
Hannes
Why is this voted down? It's a good answer.
thomasmalt
@thomasmalt care to run this "good" code ans see how it works?
Col. Shrapnel
@Col. Shrapnel as i state THIS is an imperfect Solution, BUT it is the correct solution for the Problem he described, to get a variable $Dad+Loc containing the Value 102AD, but like i said you can't access the Variable since its bad formed, so He has to think again about what he wants to archive. I prefer to show People the right way and even theyr mistakes ... not spoon-feed them
Hannes
too much code for "not spoon-feed"
Col. Shrapnel
whatever dude ...
Hannes
A: 
$string = "location:32:DaD+LoC:102AD:Ammount:294";
list($location, $Dad_Loc, $Ammount) = explode(':', $string);
samxli
+2  A: 

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);
thomasmalt
this one is good.
Col. Shrapnel
A: 

it seems nobody can do it properly

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