PHP内爆地址丢失地址的最后一部分

PHP内爆地址丢失地址的最后一部分,php,implode,Php,Implode,我有以下代码,它获取一个位置并从中提取城市和州/国家: $address_input = "555 Test Drive, Johannesburg, South Africa"; if (strpos($address_input, ',') !== false) { $arr = explode(", ", $address_input); if(count($arr) >1){ $arr[count($arr)-1] = explode(" ", $

我有以下代码,它获取一个位置并从中提取城市和州/国家:

$address_input = "555 Test Drive, Johannesburg, South Africa";

if (strpos($address_input, ',') !== false) {
    $arr = explode(", ", $address_input);
    if(count($arr) >1){
        $arr[count($arr)-1] = explode(" ", $arr[count($arr)-1])[0];
        $address = implode(", ", array_slice($arr, -2));
    }
}
地址输出为:

“南非约翰内斯堡”而不是“南非约翰内斯堡”

如何修改上面的代码以返回地址的完整最后部分,如上面的示例所示?我看到“内爆”会在所有的片段后面加一个逗号,但是我如何才能让地址的最后一段包含完整的州或国家名称呢?我不知道从这里到哪里去

谢谢大家!

像这样的

if(strpos($address_input,,')!==false){
$arr=分解(“,”,$address_input);
如果(计数($arr)>1){
$address=内爆(',',数组_片($arr,-2));
}
}

只需从分解数组中取出2和3个元素即可

$address_input = "555 Test Drive, Johannesburg, South Africa";

if (strpos($address_input, ',') !== false) {
    $arr = explode(", ", $address_input);
    if (count($arr) == 3)
        $address = $arr[1].', '.$arr[2];
}

如果输入地址始终遵循相同的模式,并且仅删除地址的第一部分,则可以采取几种不同的方法-这是另一种变体:

    $address_input = "555 Test Drive, Johannesburg, South Africa";
    $arr=explode( ",", $address_input );
    if( !empty( $arr ) ){
        array_shift( $arr );
        $address_output=implode( ",", $arr );
        echo $address_output;
    }
产出:

Johannesburg, South Africa

代码的问题在于最后一项上的
分解
。您基本上是使用
South Africa
,使用空格将其拆分,然后使用第一个单词
South
替换原始数组的最后一个条目

$address_input = "555 Test Drive, Johannesburg, South Africa";

if (strpos($address_input, ',') !== false) {
    $arr = explode(", ", $address_input);
    if(count($arr) >1){
        //$arr[count($arr)-1] = explode(" ", $arr[count($arr)-1])[0];  // by commenting this line out, I got he results you were expecting
        $address = implode(", ", array_slice($arr, -2));
    }
}

如果的模式与前面提到的模式相同,
主地址、城市、国家/地区,请尝试此操作

$address_input = "555 Test Drive, Johannesburg, South Africa";
print_r(implode(", ", array_slice(explode(", ", $address_input), -2)));

//Output:
//Johannesburg, South Africa 

工作代码如下:

您可以使用substr\u count查看字符串中是否有多个逗号。
如果有子字符串,则从第一个逗号+2个字符(逗号和空格)开始,用strpos填充字符串。
这意味着我们只进行字符串操作,不进行数组和字符串的转换

$address_input = "555 Test Drive, Johannesburg, South Africa";
if(substr_count($address_input, ",") >1){
    $address = substr($address_input, strpos($address_input, ",")+2);
}

echo $address;
// Johannesburg, South Africa
不确定如果字符串不在该模式下该怎么办,如果需要帮助,您需要在问题中包括该模式


分解后只需从地址中提取2个元素,可以删除第一个元素并使用内爆其余数组元素

$address = "555 Test Drive, Johannesburg, South Africa";
$addressToArray = explode(',',$address);
if(is_array($addressToArray)){
  array_shift($addressToArray);
  echo implode(',',$addressToArray);
}
结果

Johannesburg, South Africa

如果您没有解释代码的功能或与OPs代码的不同之处,那么答案就不完整。当OP在没有任何解释的情况下选择答案时,我总是感到惊讶。如果您没有解释代码的功能或与OPs代码的不同之处,那么答案就不完整。