PHP部分邮政编码匹配
我正在尝试创建一个简单的邮政编码表单,用户在其中输入邮政编码,如果邮政编码存在,则用户将重定向到链接 我有一个html表单:PHP部分邮政编码匹配,php,search,match,partial,postal-code,Php,Search,Match,Partial,Postal Code,我正在尝试创建一个简单的邮政编码表单,用户在其中输入邮政编码,如果邮政编码存在,则用户将重定向到链接 我有一个html表单: <form method="get" action="index.php"> <input type="text" class="form-control input-lg" name="postcode" id="postcode" placeholder="Postcode"> <span class="input-gro
<form method="get" action="index.php">
<input type="text" class="form-control input-lg" name="postcode" id="postcode" placeholder="Postcode">
<span class="input-group-btn">
<input class="btn btn-default btn-lg find" name="did_submit" id="submithome" type="submit" value="Find My Matchmaker" class="searchbutton">
</span>
</form>
以及PHP脚本:
<?php
if(isset($_GET['postcode'])){
$valid_prefixes = array(
2 => array('NH', 'AQ'),
3 => array('NZ2', 'GT5'),
4 => array('NG89', 'NG76')
);
foreach($valid_prefixes as $length => $prefixes) {
if (in_array(substr($_GET['postcode'], 0, $length), $prefixes)) {
header("Location: http://www.google.com/");
} else {
echo "<script> $('#myModal').modal('show') </script>";
}
exit;
}}
?>
它应该以这两个字母组合中的一个开头吗?然后使用:
if (in_array(substr($_GET['postcode'], 0, 2), $validatepostcode) {
// redirect
}
如果有多个长度前缀,则可以使用:
for ($i = $min_prefix_length; $i <= $max_prefix_length; $i++) {
if (in_array(substr($_GET['postcode'], 0, $i), $validatepostcode) {
// redirect
}
}
你可以使用正则表达式,比如^(NH|AQ | NZ2 | GT5)
,但如果你有很多选择,我认为这不是一个好的解决方案。好吧,如果我只有两个字母组合,这是可行的,但我会有两个字母、三个字母和四个字母的组合。(比如NG、NG3、NG90)@emisfera如果您对此特定解决方案有问题,您应该在此处进行评论,而不是编辑问题,使其看起来像是您的原始代码。抱歉,我是新手,不知道具体的工作原理。从foreach行开始,尝试向自己解释每行的功能,我相信您会看到它,如果你没有发布回复,我会把它指向你。你更正的代码(实际上是基于彼得·范德瓦尔的答案,而不是你原来的问题)有一个错误的出口代码>,这意味着它将在第一次循环后退出PHP。非常感谢,它现在可以工作了。我真的很感激
$valid_prefixes = array(
2 => array('NH', 'AQ'),
3 => array('NZ2', 'GT5'),
);
foreach($valid_prefixes as $length => $prefixes) {
if (in_array(substr($_GET['postcode'], 0, $length), $prefixes) {
// redirect
}
}