检查/匹配数组中部分字符串的字符串

时间:2017-12-02 23:00:23

标签: php regex postal-code

我正在尝试将完整的英国邮政编码与部分邮政编码相匹配。 获取用户邮政编码,即g22 1pf,并查看数组/数据库中是否存在匹配/部分匹配。

//Sample data
$postcode_to_check= 'g401pf';
//$postcode_to_check= 'g651qr';
//$postcode_to_check= 'g51rq';
//$postcode_to_check= 'g659rs';
//$postcode_to_check= 'g40';

$postcodes = array('g657','g658','g659','g659pf','g40','g5');
$counter=0;

foreach($postcodes as $postcode){
    $postcode_data[] = array('id' =>$counter++ , 'postcode' => $postcode, 'charge' => '20.00');
}

我确实有一些代码,但这只是比较数据库中固定长度的字符串。我需要数组/数据库中的字符串是动态的。

数据库可能包含“g22”这将是一个匹配,它也可能包含更多或更少的邮政编码,即“g221”或“g221p”,这也是一个匹配。它可能包含“g221q”或“g221qr”这些不匹配。

帮助感谢,谢谢

修改。

我可能想过这个。以下伪代码似乎按预期运行。

check_delivery('g401pf');
//this would match because g40 is in the database.

check_delivery('g651dt');
// g651dt this would NOT match because g651dt is not in the database.

check_delivery('g524pq');
//g524pq this would match because g5 is in the database.

check_delivery('g659pf');
//g659pf this would match because g659 is in the database.

check_delivery('g655pf');
//g655pf this would not match, g665 is not in the database

//expected output, 3 matches

function check_delivery($postcode_to_check){

    $postcodes = array('g657','g658','g659','g659pf','g40','g5');       
    $counter=0;

    foreach($postcodes as $postcode){

        $stripped_postcode = substr($postcode_to_check,0, strlen($postcode));

        if($postcode==$stripped_postcode){
            echo "Matched<br><br>";
          break;
        } 
    }
}

2 个答案:

答案 0 :(得分:0)

       <?php
    $postcode_to_check= 'g401pf';

    $arr = preg_split("/\d+/",$postcode_to_check,-1, PREG_SPLIT_NO_EMPTY);
    preg_match_all('/\d+/', $postcode_to_check, $postcode);
    $out = implode("",array_map(function($postcode) {return implode("",$postcode);},$postcode));
    $first_char = mb_substr($arr[1], 0, 1);

    $MatchingPostcode=$arr[0].''.$out.''.$first_char;
    echo $MatchingPostcode;



 SELECT * FROM my_table WHERE column_name LIKE '%$MatchingPostcode%';

这是一个肮脏的解决方案,但它将解决您的问题。这样的事情应该在前端或数据库中处理,但如果你必须在php中进行处理,那么这是一个解决方案。

因此,此代码将匹配包含g401p的任何内容。如果您不希望在结尾开始时匹配,请从您不想匹配的部分中删除%。在我提供给你的情况下,它将搜索具有g401p

的每个列记录

答案 1 :(得分:0)

检查长度并将要比较的长度剥离到相同的长度。

function check_delivery($ postcode_to_check){

$postcodes = array('g657','g658','g659','g659pf','g40','g5');       
$counter=0;

foreach($postcodes as $postcode){

    $stripped_postcode = substr($postcode_to_check,0, strlen($postcode));

    if($postcode==$stripped_postcode){
        echo "Matched<br><br>";
      break;
    } 
}

}