2016-03-24 64 views
2

我有一個API調用,返回具有以下格式的字段meetingAddress。 街道「 」城市「,」州ZipCode。本例中的「」是顯示匹配字符落入字符串的位置。從字符串返回城市和州

我已經擺弄了substr和strpos,但由於我的極限經驗似乎無法讓它工作。我正在寫一個函數來接收地址並返回城市和州。

$str needs to be populated with the MeetingAddress data 
$from = "#xD;"; - this is always before the city 
$to = ","; - this is after the city 
echo getStringBetween($str,$from,$to); 
function getStringBetween($str,$from,$to) 
{ 
$sub = substr($str, strpos($str,$from)+strlen($from),strlen($str)); 
return substr($sub,0,strpos($sub,$to)); 
} 

下面是返回內容的確切示例。

 <d:MeetingAddress>44045 Five Mile Rd&#xD; 
     Plymouth, MI 48170-2555</d:MeetingAddress> 

這是第二個例子:

 <d:MeetingAddress>PO Box 15526&#xD; 
     Houston, TX 77220-5526</d:MeetingAddress> 
+2

後從API返回的字符串的確切實例。 – AbraCadaver

+0

字符串在哪裏?提供一個你得到的迴應的例子。 –

+0

我附加了對問題的回答。謝謝! – Johanna

回答

0

你可以像下面

$string = '44045 Five Mile Rd&#xD;Plymouth, MI 48170-2555'; 

list($address,$cityAndState) = explode('#xD;',$string); 
list($city,$state) = explode(',',$cityAndState); 
echo $address; 
echo $city; 
echo $state; 
+1

該代碼是如此美麗,它讓我變得有點眼淚! :D謝謝@vishnu! – Johanna

0

只需使用explode()功能:

$str = '<d:MeetingAddress>44045 Five Mile Rd&#xD;Plymouth, MI 48170-2555</d:MeetingAddress>'; 
$tmp = explode(';', $str); 
$details = explode(',',$tmp[1]); 
$details[1] = substr(trim($details[1]),0,2); 
var_dump($details); 

輸出:

Array 
(
    [0] => Plymouth 
    [1] => MI 
) 
1
$str = "<d:MeetingAddress>44045 Five Mile Rd&#xD;Plymouth, MI 48170-2555</d:MeetingAddress>"; 
preg_match('/&#xD;(.*),(.*) /', $str, $matches); 

$matches[1]是城市,$matches[2]是國家

+1

短而優雅,很好! +1 – mitkosoft