用PHP从字符串中提取城市和邮政编码

2022-02-27 00:00:00 match php preg-match

我需要PHP中的一种快速通用方法来从输入字符串中提取城市和邮政编码(如果可用)信息。

该字符串可以采用以下形式

  1. $input_str="康涅狄格州纽黑文市主街123号";
  2. $INPUT_STR="康涅狄格州纽黑文市主街123号,邮编06510";
  3. $input_str="美国康涅狄格州纽黑文";
  4. $INPUT_STR="CT 06510纽黑文";

我认为对于(1)&;(3),至少可以用","分解输入字符串,然后循环数组以找到2位状态字符并忽略它。但我被困在了这一点之外。

$search_values = explode(',' ,$input_str);
foreach($search_values as $search)
{
    $trim_search = trim($search);   // Remove any trailing white spaces

    // If the 2 digit State is provided without Zipcode, ignore it
    if (strlen($trim_search) == 2)
    {
        //echo 'Ignoring State Without Zipcode: ' . $search . '<br>';
        continue;
    }

    ...

解决方案

我不是使用正则表达式最好的,但这里有一个查找带或不带邮政编码的双字符状态的方法。

正则表达式:(([A-Z]{2})|[0-9]{5})+

Fiddle

但是,如果您希望仅在州和邮政编码同时匹配时才进行匹配,请查看以下内容: 正则表达式:(([A-Z]{2})(s*[0-9]{5}))+

Fiddle

希望这能有所帮助。

编辑

class Extract  {

    private $_string;

    private $_sections = array();

    private $_output = array();

    private $_found = array();

    private $_original_string;

    private $_countries = array (
        'United States',
        'Canada',
        'Mexico',
        'France',
        'Belgium',
        'United Kingdom',
        'Sweden',
        'Denmark',
        'Spain',
        'Australia',
        'Austria',
        'Italy',
        'Netherlands'
    );

    private $_zipcon = array();

    private $ZIPREG = array(
        "United States"=>"^d{5}([-]?d{4})?$",
        "United Kingdom"=>"^(GIR|[A-Z]d[A-Zd]??|[A-Z]{2}d[A-Zd]??)[ ]??(d[A-Z]{2})$",
        "Germany"=>"((?:0[1-46-9]d{3})|(?:[1-357-9]d{4})|(?:[4][0-24-9]d{3})|(?:[6][013-9]d{3}))",
        "Canada"=>"^([ABCEGHJKLMNPRSTVXY]d[ABCEGHJKLMNPRSTVWXYZ])s*(d[ABCEGHJKLMNPRSTVWXYZ]d)$",
        "France"=>"^(F-)?((2[A|B])|[0-9]{2})[0-9]{3}$",
        "Italy"=>"^(V-|I-)?[0-9]{5}$",
        "Australia"=>"^(0[289][0-9]{2})|([1345689][0-9]{3})|(2[0-8][0-9]{2})|(290[0-9])|(291[0-4])|(7[0-4][0-9]{2})|(7[8-9][0-9]{2})$",
        "Netherlands"=>"^[1-9][0-9]{3}s?([a-zA-Z]{2})?$",
        "Spain"=>"^([1-9]{2}|[0-9][1-9]|[1-9][0-9])[0-9]{3}$",
        "Denmark"=>"^([D-d][K-k])?( |-)?[1-9]{1}[0-9]{3}$",
        "Sweden"=>"^(s-|S-){0,1}[0-9]{3}s?[0-9]{2}$",
        "Belgium"=>"^[1-9]{1}[0-9]{3}$"
    ); // thanks to http://www.pixelenvision.com/1708/zip-postal-code-validation-regex-php-code-for-12-countries/

    public function __construct($string) {

        $this->_output = array (

            "state" => "",
            "city" => "",
            "country" => "",
            "zip" => "",
            "street" =>"",
            "number" => ""
        );
        $this->_original_string = $string;
        $this->_string = $this->normalize(trim($string));


        // create an array of patterns in order to extract zip code using the country list we already have
        foreach($this->ZIPREG as $country => $pattern) {
            $this->_zipcon[] = $pattern = preg_replace( array("/^/","/\$/"),array("",""), $pattern);
        }

        $this->init();

    }

    protected function init() {

        $this->getData(); // get data that can be found without breaking up the string.

        $this->_sections = array_filter(explode(',', trim($this->_string)));  // split each section

        if(!empty($this->_sections)) {
            foreach($this->_sections as $i => $d) {
                $d = preg_replace(array("/s+/", "/s([?.!])/"),  array(" ","$1"), $d ); 
                $this->_sections[$i] = trim($this->normalize($d));  // normalize strin to have one spacing between each word
            }
        } else {
            $this->_sections[] = $this->_string;    
        }       

        // try to match what's missing with has already been found
        $notFound = $this->getNotFound();
        if(count($notFound)==1 && count($this->_found)>1) {
            $found = $this->getFound();
            foreach($found as $string) {
                $notFound[0] = preg_replace("/$string/i", "", $notFound[0]);
            }
            $this->_output["city"] = $notFound[0];
            $this->_found[] = $this->_output["city"];
            $this->remove($this->_output["city"]);
        }   
    }

    public function getSections() {
        return $this->_sections;
    }   

    protected function normalize($string) {
        $string = preg_replace(array("/s+/", "/s([?.!])/"),  array(" ","$1"), trim($string));
        return $string;
    }

    protected function country_from_zip($zip) {
        $found = "";
        foreach($this->ZIPREG as $country => $pattern) {
            if(preg_match ("/".$pattern."/", $zip)) {
                $found = $country;
                break;
            }
        }
        return $found;
    }

    protected function getData() {
        $container = array();
        // extract zip code only when present beside state, or else five digits are meaningless

        if(preg_match ("/[A-Z]{2,}s*(".implode('|', $this->_zipcon).")/", $this->_string) ){
            preg_match ("/[A-Z]{2,}s*(".implode('|', $this->_zipcon).")/", $this->_string, $container["state_zip"]);

            $this->_output["state"] = $container["state_zip"][0];
            $this->_output["zip"] = $container["state_zip"][1];
            $this->_found[] = $this->_output["state"] . " ". $this->_output["zip"];
            // remove from string once found
            $this->remove($this->_output["zip"]);   
            $this->remove($this->_output["state"]);

            // check to see if we can find the country just by inputting zip code
            if($this->_output["zip"]!="" ) {
                $country = $this->country_from_zip($this->_output["zip"]);
                $this->_output["country"] = $country;
                $this->_found[] = $this->_output["country"];
                $this->remove($this->_output["country"]);
            }
        } 

        if(preg_match ("/([A-Z]{2,})/", $this->_string)) {
            preg_match ("/([A-Z]{2,})/", $this->_string, $container["state"]);  
            $this->_output["state"] = $container["state"][0];
            $this->_found[] = $this->_output['state'];
            $this->remove($this->_output["state"]);
        }

        // if we weren't able to find a country based on the zip code, use the one provided (if provided)
        if($this->_output["country"] == "" && preg_match("/(". implode('|',$this->_countries)  . ")/i", $this->_string) ){
            preg_match ("/(". implode('|',$this->_countries)  . ")/i", $this->_string, $container["country"]);
            $this->_output["country"] = $container["country"][0];
            $this->_found[] = $this->_output['country'];
            $this->remove($this->_output["country"]);
        }   

        if(preg_match ("/([0-9]{1,})s+([.\-a-zA-Zs*]{1,})/", $this->_string) ){
            preg_match ("/([0-9]{1,})s+([.\-a-zA-Zs*]{1,})/", $this->_string, $container["address"]);
            $this->_output["number"] = $container["address"][1];
            $this->_output["street"] = $container["address"][2];
            $this->_found[] = $this->_output["number"] . " ". $this->_output["street"];
            $this->remove($this->_output["number"]);
            $this->remove($this->_output["street"]);
        }       


        //echo $this->_string;
    }

    /* remove from string in order to make it easier to find missing this */
    protected function remove($string, $case_sensitive = false) {
        $s = ($case_sensitive==false ? "i" : "");
        $this->_string = preg_replace("/".$string."/$s", "", $this->_string);
    }

    public function getNotFound() {
        return array_values(array_filter(array_diff($this->_sections, $this->_found)));
    }

    public function getFound() {
        return $this->_found;   
    }

    /* outputs a readable string with all items found */
    public function toString() {
        $output = $this->getOutput();
        $string = "Original string: [ ".$this->_original_string.' ] ---- New string: [ '. $this->_string. ' ]<br>';
        foreach($output as $type => $data) {
            $string .= "-".$type . ": " . $data. '<br>';    
        }   
        return $string;
    }

    /* return the final output as an array */
    public function getOutput() {
        return $this->_output;  
    }   

}



$array = array();
$array[0] = "123 Main Street, New Haven, CT 06518";
$array[1] = "123 Main Street, New Haven, CT";
$array[2] = "123 Main Street, New Haven,                            CT 06511";
$array[3] = "New Haven,CT 66554, United States";
$array[4] = "New Haven, CT06513";
$array[5] = "06513";
$array[6] = "123 Main    Street, New Haven CT 06518, united states";

$array[7] = "1253 McGill College, Montreal, QC H3B 2Y5"; // google Montreal  / Canada
$array[8] = "1600 Amphitheatre Parkway, Mountain View, CA 94043"; // google CA  / US
$array[9] = "20 West Kinzie St., Chicago, IL 60654"; // google IL / US
$array[10] = "405 Rue Sainte-Catherine Est, Montreal, QC"; // Montreal address shows hyphened street names
$array[11] = "48 Pirrama Road, Pyrmont, NSW 2009"; // google Australia


foreach($array as $string) {
    $a = new Extract($string);

    echo $a->toString().'<br>'; 
}

使用上面代码中的示例,它应该会输出:

Original string: [ 123 Main Street, New Haven, CT 06518 ] ---- New string: [ , , ]
-state: CT
-city: New Haven
-country: United States
-zip: 06518
-street: Main Street
-number: 123

Original string: [ 123 Main Street, New Haven, CT ] ---- New string: [ , , ]
-state: CT
-city: New Haven
-country: 
-zip: 
-street: Main Street
-number: 123

Original string: [ 123 Main Street, New Haven, CT 06511 ] ---- New string: [ , , ]
-state: CT
-city: New Haven
-country: United States
-zip: 06511
-street: Main Street
-number: 123

Original string: [ New Haven,CT 66554, United States ] ---- New string: [ , , ]
-state: CT
-city: New Haven
-country: United States
-zip: 66554
-street: 
-number: 

Original string: [ New Haven, CT06513 ] ---- New string: [ , ]
-state: CT
-city: New Haven
-country: United States
-zip: 06513
-street: 
-number: 

Original string: [ 06513 ] ---- New string: [ 06513 ]
-state: 
-city: 
-country: 
-zip: 
-street: 
-number: 

Original string: [ 123 Main Street, New Haven CT 06518, united states ] ---- New string: [ , , ]
-state: CT
-city: New Haven
-country: United States
-zip: 06518
-street: Main Street
-number: 123

Original string: [ 1253 McGill College, Montreal, QC H3B 2Y5 ] ---- New string: [ , , ]
-state: QC
-city: Montreal
-country: Canada
-zip: H3B 2Y5
-street: McGill College
-number: 1253

Original string: [ 1600 Amphitheatre Parkway, Mountain View, CA 94043 ] ---- New string: [ , , ]
-state: CA
-city: Mountain View
-country: United States
-zip: 94043
-street: Amphitheatre Parkway
-number: 1600

Original string: [ 20 West Kinzie St., Chicago, IL 60654 ] ---- New string: [ , , ]
-state: IL
-city: Chicago
-country: United States
-zip: 60654
-street: West Kinzie St.
-number: 20

Original string: [ 405 Rue Sainte-Catherine Est, Montreal, QC ] ---- New string: [ , , ]
-state: QC
-city: Montreal
-country: 
-zip: 
-street: Rue Sainte-Catherine Est
-number: 405

Original string: [ 48 Pirrama Road, Pyrmont, NSW 2009 ] ---- New string: [ , , ]
-state: NSW
-city: Pyrmont
-country: Australia
-zip: 2009
-street: Pirrama Road
-number: 48

如果要提取实际存储的值以便可以使用。您需要调用getOutput()。这将返回一个包含所有值的数组。如果我们使用此方法获取列表中的第一个地址并输出它的值,它应该会输出:

Array
(
    [state] => CT
    [city] => New Haven
    [country] => United States
    [zip] => 06518
    [street] => Main Street
    [number] => 123
)

请注意,这个类可以进行极大的优化和改进。这是我在一小时内想出来的,所以我不能保证它对所有类型的输入都有效。本质上,您必须确保用户至少努力使用逗号来分隔地址的各个部分。您还需要确保提供了大写的州和有效的五位邮政编码。

几条规则

  1. 若要提取邮政编码,必须在2个字符的有效状态旁边提供有效的邮政编码。例如:CT 06510。如果没有州,简单地输入五位数是没有意义的,因为街道号码中也可以有五位数。(无法区分两者)。

  2. 街道和数字只能在顺序提供数字和单词的情况下提取。示例:123 Main Street。它还必须用逗号分隔,否则它将捕获数字后面的所有单词。例如123 Main Street New Haven, CT 06518,代码将表示街道和号码为123 Main Street New Haven,而不是123 Main Street

  3. 简单地输入五位邮政编码不起作用。

  4. 如果未提供国家/地区,只要有有效的邮政编码,它就会猜测国家/地区(请参阅上面的邮政编码列表及其各自的国家/地区)。

  5. 它假定不会提供连字符(特别是对于城市名称)。这可以在以后修改。(需要修改Regex以适应城市和街道名称的连字符单词)。(已修复)

  6. 底线是,如果您有时间更改和修改正则表达式并相应地对其进行自定义,您可以做得更多。

我强烈建议您使用表单(如果您还没有这样做的话),以便轻松地捕获输入中提供的地址。这可能会让你的生活轻松很多。

快速使用

$Extract = new Extract("123 Main Street, New Haven, CT 06518");
$foundValues = $Extract->getOutput();

相关文章