从字符串返回城市和州

时间:2016-03-24 17:34:59

标签: php regex

我有一个API调用返回一个字段meetingAddress,格式如下。 街"
"城市","州的邮编。 ""在这个例子中,显示匹配的字符落入字符串的位置。

我已经摆弄了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>

3 个答案:

答案 0 :(得分: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 :(得分: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;

答案 2 :(得分: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
)