简体   繁体   中英

php form, check array and redirect

first time using stack overflow - I know how to copy and edit some PHP but wouldn't call myself a dev.

I have a form, a postcode lookup function, the idea is a user enters their post/zip code and the php redirects them to the relevant page, if no match then it goes to a generic page. I eventually want to log the postcodes in a database but thats not important now.

the code works perfectly, I just want to finesse it to use wildcards for postcodes-

if (isset($_GET['did_submit'])) {

    $zip = $_GET['zip'];

    $loc1 = array (A1,A2,A3);
    $loc2 = array (BB1,BB2,BB3);
    $loc3 = array (PR8,PR9);

    if(in_array($zip, $loc1)) {
        header('Location: /new/location0/');
    }else if(in_array($zip, $loc2)) {
        header('Location: /new/location1/');
    }else if(in_array($zip, $loc3)) {
        header('Location: /new/location2/');
    }else {
        header('Location: /new/location-generic/');
    }
}

Essentially what I want to do is have Lowercase and uppercase characters included, and also make it a wildcard (A1*, A2*) Etc,

Is this possible - how am I best going about this?

I think you are looking for the preg_match function, see syntax from PhP Manual below:

preg_match ( string $pattern , string $subject , array &$matches = null , int $flags = 0 , int $offset = 0 ) : int|false

This can be used to identify a substring within a larger string.

First note your array strings need to be quoted. Change to:

$loc1 = array ('A1','A2','A3');
$loc2 = array ('BB1','BB2','BB3');
$loc3 = array ('PR8','PR9');

To do a case insensitive match of postcode to the array you can use stripos() like this:

foreach ($loc1 as $prefix) {
    if (stripos($zip, $prefix) === 0) {
        header('Location: /new/location0/');
        die;
    }
}

That checks to see if the $prefix exists in the $zip at exactly the beginning (notice the strict type comparison using === )

Here's a suggestion for an improvement. You can put all you prefixes in a single array and use the key as the location - something like this:

$locations = [
    '/new/location0/' => ['A1','A2','A3'],
    '/new/location1/' => ['BB1','BB2','BB3'],
    '/new/location2/' => ['PR8','PR9']
];

foreach ($locations as $location => $prefixes) {
    foreach ($prefixes as $prefix) {
        if (stripos($zip, $prefix) === 0) {
            header('Location: ' . $location);
            die;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM