我有一组地址存储为单独的字符串。这是这些字符串的可能值:
"Staples Center, 555 Test Drive, Los Angeles, CA 98112"
"555 Test Drive, Los Angeles, CA 98112"
"Los Angeles, CA"
"Los Angeles, CA 98112"
"Los Angeles"
日期将始终采用这种格式,其中可以包含场所名称,街道地址,城市,州和邮政编码
我只想从这些字符串中动态提取城市和州:
$addresses_array = array(
"Staples Center, 555 Test Drive, Los Angeles, CA 98112",
"555 Test Drive, Los Angeles, CA 98112",
"Los Angeles, CA",
"Los Angeles, CA 98112",
"Los Angeles"
);
foreach ($addresses_array as $address) {
if (strpos($address, ',') !== false) {
// extract the city and state
}
}
鉴于地址值的模式,我是否可以做一些事情来基于逗号提取城市和州?
我看到的是城市将永远是字符串中的最后一个逗号。
答案 0 :(得分:2)
如果我没看错的话,您需要最后两个项目(如果有)。
使用爆炸,然后内爆最后两个项目。
$addresses_array = array(
"Staples Center, 555 Test Drive, Los Angeles, CA 98112",
"555 Test Drive, Los Angeles, CA 98112",
"Los Angeles, CA",
"Los Angeles, CA 98112",
"Los Angeles"
);
foreach ($addresses_array as &$address) {
$arr = explode(", ", $address);
$address = implode(", ", array_slice($arr, -2));
}
var_dump($addresses_array);
输出:
array(5) {
[0]=>
string(21) "Los Angeles, CA 98112"
[1]=>
string(21) "Los Angeles, CA 98112"
[2]=>
string(15) "Los Angeles, CA"
[3]=>
string(21) "Los Angeles, CA 98112"
[4]=>
&string(11) "Los Angeles"
}
如果您不希望使用zip,那么如果$ arr计数大于一个,则可以爆炸空间中的最后一个项目。
foreach ($addresses_array as &$address) {
$arr = explode(", ", $address);
if(count($arr) >1){
$arr[count($arr)-1] = explode(" ", $arr[count($arr)-1])[0];
$address = implode(", ", array_slice($arr, -2));
}
}
输出:
array(5) {
[0]=>
string(15) "Los Angeles, CA"
[1]=>
string(15) "Los Angeles, CA"
[2]=>
string(15) "Los Angeles, CA"
[3]=>
string(15) "Los Angeles, CA"
[4]=>
&string(11) "Los Angeles"
}
答案 1 :(得分:-1)
您可以同时使用explode
和count
功能
$addresses_array = array(
"Staples Center, 555 Test Drive, Los Angeles, CA 98112",
"555 Test Drive, Los Angeles, CA 98112",
"Los Angeles, CA",
"Los Angeles, CA 98112",
"Los Angeles"
);
foreach ($addresses_array as $address) {
$addr = explode(",",$address);
switch (count($addr))
{
case 1:
case 2:
echo $addr[0];
break;
case 3:
echo $addr[1];
break;
case 4:
echo $addr[2];
break;
}
}