我想把这个字符串拆分成“Source:Web”,“Pics:1”等部分......在我的网站中使用它。 从“Lat:”和“Lon:”我只需要提取数字。
<cap>
Source: Web | Pics: 1 | Frame: 2 | Date: 4-25-2011 | On: App | Lat: 51.2222 | Lon: 7.6555
</cap>
最好的方法是什么?我读到了关于explode()的内容,但我没有让它发挥作用。 干杯
答案 0 :(得分:4)
以下是我使用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'
答案 1 :(得分:1)
这是一个荒谬的单行程,应该永远不会被使用,但它不使用循环(我讨厌循环)。我也喜欢练习我的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);
结果
Array
(
[Source] => Web
[Pics] => 1
[Frame] => 2
[Date] => 4-25-2011
[On] => App
[Lat] => 51.2222
[Lon] => 7.6555
)
答案 2 :(得分:0)
$pieces = explode(' | ','Source: Web...'); //Rest of string in there.
$items = array();
foreach ($pieces as $piece) {
$parts = explode(': ', $piece);
$items[$parts[0]] = $parts[1];
}
答案 3 :(得分:0)
$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);
答案 4 :(得分:0)
$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);
答案 5 :(得分:0)
试试这个。它将拆分它们并创建一个关联数组:
$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);
答案 6 :(得分:0)
$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]);
答案 7 :(得分:-1)
你是对的。 explode是最好的功能。