2016-03-24 62 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