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 a开发者_运维问答nd 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!
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.
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.
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 ")
$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
精彩评论