我怎么能把streetnr和street从一个字符串中分开呢


How can I divide streetnr and street out of one 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,5a

我的想法是在每一个空白"。。。然后我反转数组,看看第一个元素是否只是一个字母。如果是,我就把它放到街上。然后我检查下一个元素。如果只有数字,我会把它放在streetnr。。。依此类推

我把它作为PHP培训的练习。虽然我是regex的超级粉丝,但我想在没有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>";
 ?>

使用正则表达式

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

如果街道的格式正确,并且$match是一个包含[1]=街道名称、[2]=街道编号的数组,则preg_match返回true。

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

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