tags:

views:

211

answers:

4

I have a string of data like below and I've been struggling trying to figure out how to split it up so that I can use it efficiently.

"United States FirstName: Mike LastName: Doe City: Chicago"

I need to split up the string in to substrings and the list may not always be in the same order.

For example it could vary like below:

"United States City: Chicago FirstName: Mike LastName: Doe"
"CanadaFirstName: Mike City: Chicago LastName: Doe"

I need to find which parameter comes first after 'United States'. It could be 'City:', 'FirstName:' or 'LastName:'. And, I also need to know the start position of the first parameter.

Thanks in advance!

A: 

First, strip off the "United States ": $str2 = substr($string, 0, strlen("United States "))

Then find the field: preg_match('/^([^:]+): /', $str2)

The position of the first parameter should be constant: strlen("United States ")

SHiNKiROU
I should say that it wont always start with "United States", it could be something else.
mike
@mike This should help, `preg_match('/^([^\:]+)\s+(\w+)\:/', $string)` The first backref is the "United States", and the second backref is the first field.
SHiNKiROU
A: 
$string = "United States FirstName: Mike LastName: Doe City: Chicago";
$i = strpos($string, ":");           // Find the first colon
while ($string[$i] != " ") { $i--; } // work backwards until we hit a space
// First parameter's name now starts at $i + 1
Ben S
That space may not always be there either :(
mike
Well if there's no well defined structure, we can't be expected to parse it.
Ben S
FirstName: City: LastName: will always be in there. I just don't know if there will be a space around them.
mike
+1  A: 

As long as FirstName:, LastName: and City: will always be in there, you should be able to just get the positions of all three and see which one occurs first with min().

$string = "United States City: Chicago FirstName: Mike LastName: Doe";
$firstname = strpos($string, 'FirstName:');
$lastname = strpos($string, 'LastName:');
$city = strpos($string, 'City:');

$position = min($firstname, $lastname, $city);
switch($position){
   case $firstname:
      $first_parameter = 'FirstName:';
      break;
   case $lastname:
      $first_parameter = 'LastName:';
      break;
   case $city:
      $first_parameter = 'City:';
      break;
}

You'll have your first parameter and the position.

munch
+1  A: 

I think the cleanest and most straightforward way to do this (though a sexy regex is tempting) is to put your parameters in an array and foreach through it.

$params = array(
    'FirstName:',
    'LastName:',
    'City:',
);

$first = null; # First parameter
$first_pos = null; # First parameter position

foreach($params as $var)
{
    $pos = strpos($string, $var);
    if($pos < $first_pos || null === $first_pos)
    {
        $first = $var;
        $first_pos = $pos;
    }
}

If you change your params, just change the array.

banzaimonkey