I want to split this string up into parts like "Source: Web", "Pics: 1" ... to use it within my website. From the "Lat:" and "Lon:" I need to extract just the numbers.
<cap>
Source: Web | Pics: 1 | Frame: 2 | Date: 4-25-2011 | On: App | Lat: 51.2222 | Lon: 7.6555
</cap>
What's the best way to do it? I read about explode() but I don't get it to work. Cheers
Here is a bit of code I whipped up using explode
(DEMO)
<?php
$str = "Source: Web | Pics: 1 | Frame: 2 | Date: 4-25-2011 | On: App | Lat: 51.2222 | Lon: 7.6555";
$arr = explode(" | ", $str);
foreach ($arr as $item){
$arr2 = explode(": ", $item);
$finalArray[$arr2[0]]=$arr2[1];
}
print_r($finalArray);
?>
RESULT
Array
(
[Source] => Web
[Pics] => 1
[Frame] => 2
[Date] => 4-25-2011
[On] => App
[Lat] => 51.2222
[Lon] => 7.6555
)
USAGE
echo $finalArray['Lon']; //yields '7.6555'
Here's a ridiculous one-liner that should probably never be used, but it uses no loops (i hate loops). I also like to practice my REs
$str = 'Source: Web | Pics: 1 | Frame: 2 | Date: 4-25-2011 | On: App | Lat: 51.2222 | Lon: 7.6555';
preg_match( sprintf( '~%s~', implode(array_map( function($val){ if ($val) return sprintf( '%1$s:\s(?P<%1$s>.*?)(?:(?:\s\|\s)|(?:$))', $val ); }, preg_split( '~:.*?(?:(?:\s\|\s)|(?:$))~', $str ) ) ) ), $str, $m );
print_r($m);
result
Array
(
[Source] => Web
[Pics] => 1
[Frame] => 2
[Date] => 4-25-2011
[On] => App
[Lat] => 51.2222
[Lon] => 7.6555
)
$pieces = explode(' | ','Source: Web...'); //Rest of string in there.
$items = array();
foreach ($pieces as $piece) {
$parts = explode(': ', $piece);
$items[$parts[0]] = $parts[1];
}
$string = "Source: Web | Pics: 1 | Frame: 2 | Date: 4-25-2011 | On: App | Lat: 51.2222 | Lon: 7.6555";
$pieces = explode("|", $string);
print_r($pieces);
$items = explode(' | ', "Source: Web | Pics: 1 | Frame: 2 | Date: 4-25-2011 | On: App | Lat: 51.2222 | Lon: 7.6555");
foreach ($items as $item) {
$new_data = explode(': ', $item);
$my_array[$new_data[0]] = $new_data[1];
}
print_r($my_array);
Try this one. It will split them and create an associative array:
$string = 'Source: Web | Pics: 1 | Frame: 2 | Date: 4-25-2011 | On: App | Lat: 51.2222 | Lon: 7.6555';
$list = explode('|', $string);
$assoc = array();
foreach($list as $part) {
list($key, $val) = explode(':', $part);
$assoc[trim($key)] = trim($val);
}
print_r($assoc);
$val =<<<END
<cap>
Source: Web | Pics: 1 | Frame: 2 | Date: 4-25-2011 | On: App | Lat: 51.2222 | Lon: 7.6555
</cap>
END;
$bits = split("[:|]", $val);
$lat = trim($bits[11]);
$lon = trim($bits[13]);
You are correct. explode is the best function for this.
精彩评论