我已經用它作爲我的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>";
?>
所以,你得到一個解決方案之前,你真的需要定義標準如何確定「街道」部分與「街道號碼」。你能用現實世界的術語解釋要求嗎? –
好吧,我編輯了這個問題,爲此! – Susanne92
@ Susanne92 - 他們總是會以這種格式?你不會有街道號碼的第一行,然後是街道名稱? – andrewsi