用正则表达式拆分地址字符串

时间:2018-03-26 11:25:15

标签: php regex string preg-match

如何使用正则表达式拆分这样的字符串?

  

Route de la Comba 32 1484 Aumont(FR)

     

Chemin de la Vignetta 1 1617 Remaufens(FR)

     

Route du Village 136 1609 Besencens(FR)

  • 地址: Route de la Comba 32
  • 邮政编码: 1484
  • 城市: Aumont(FR)

注意:在32到1484之间有2个空格(在这个问题中显示为一个空格)

2 个答案:

答案 0 :(得分:1)

怎么样:

preg_match('/^(.+?)\h{2}(\d{4,5})\h+(.+)$/', $inputString, $matches);

<强>解释

^           : beginning of line
  (.+?)     : group 1, 1 or more any character, not greedy, address
  \h{2}     : 2 horizontal spaces
  (\d{4,5}) : group 2, 4 upto 5 digits, postal code
  \h+       : 1 horizontal space
  (.+)      : group 3, 1 or more any character, city
$           : end of line

答案 1 :(得分:0)

如果格式始终相同,您可以尝试使用implodeexplode使用双空格:

$str = "Route de la Comba 32  1484 Aumont (FR)";
$splitByDoubleSpace = explode("  ", $str);
$splitBySingleSpace = explode(" ", $splitByDoubleSpace[1]);
$city = implode(" ", array_slice($splitBySingleSpace, 1)); // Return the array except the first entry

echo sprintf(
    'Address: %s<br>Postal code: %s<br>City: %s',
    $splitByDoubleSpace[0],
    $splitBySingleSpace[0],
    implode(" ", array_slice($splitBySingleSpace, 1))
);

那会给你:

Address: Route de la Comba 32
Postal code: 1484
City: Aumont (FR)

Demo Php