如何将streetnr和street分成一个String?

时间:2013-07-15 17:06:44

标签: php

我想将一个String分成var street和streetnr。我怎么能用PHP做到这一点?

数据如下:

Bakerstreet 5
Wild Street 5 a
Best Street 5a
Simplestreet

我有没有数字的街道和有字母的街道......我怎么能这样做?

所以街道应该总是像

var street = Bakerstreet,Wild Street,Best Street,Simplestreet

var streetnr应始终为= 5,5 a,5a

我的想法是在每个空格“”之后爆炸字符串......然后我反转数组并查看第一个元素是否只是一个字母。如果是,我把它放到streetnr。然后我检查下一个元素。如果只有数字,我把它放到streetnr ......等等

3 个答案:

答案 0 :(得分:2)

我已将此作为我的PHP培训练习。虽然我是正则表达式的忠实粉丝,但我想在没有em的情况下做到这一点,并提出以下建议:

<?php
$addr = array("Bakerstreet 5",
"Wild Street 5 a",
"Best Street 5a",
"Simplestreet",
"Won't Work 47a Suite 18b",
"1st Street 10b ",
"Route 66 12a " 
);


echo "<h1>Address-Parsing</h1><ol>";
foreach ($addr as $ad) 
{
  $no=""; // Number
  $st=""; // Street
  $GotNo = false;
  $r = strrev(trim($ad));
  echo "<li>ad=$ad";
  do {
    while ($r{0}=="0") {// special handling for leading "0"s (in reverted string) which are ignored by sscanf...
        if (!$GotNo) $no = "0" . $no;
        else $st = "0" . $st;
        $r = substr($r,1);
    }
    $d = sscanf($r,"%d"); // get number
    $s = sscanf($r,"%c"); // get string
    if (is_null($d[0]) && !$GotNo) {
      // no matching number and have not matched no yet - so this must be string following the nr
      $no = strrev($s[0]) . $no;
      $r = substr($r,strlen($s[0])); // remove match
    } elseif (!$GotNo) {
      $no = strrev($d[0]) . $no;
      $GotNo = true;
      $r = substr($r,strlen($d[0])); // remove match
    } else {// we already have a number, so any text must be streetname
      $st = strrev($r) . $st;
      $r="";
    }
    if ($r !== trim($r)) {$st = " " . $st; $r = trim($r);}
  } while (0<strlen($r));
  $st = trim( $st);
  if (empty($st)) {// might happen when no number was found...
    $st=$no;
    $no="";
  }
  echo "|st=$st|no=$no|</li>";
}
echo "</ol>";

 ?>

答案 1 :(得分:1)

使用正则表达式

preg_match('~^\s*(.*)\s+([0-9]+\s*[a-zA-Z]{0,1})\s*$~', $street, $match);

如果街道格式正确,则preg_match返回true,$ match是包含[1] =街道名称的数组,[2] = streetnr。

答案 2 :(得分:0)

您可以使用以下正则表达式进行匹配:

preg_match('/^(.+?)(?:\s+(\d.*))?$/', $street, $matches);
$street = $matches[1];
if (count($matches) == 3)
  $streetnr = $matches[2];