简体   繁体   English

如何在变量中检测地址或邮政编码

[英]How to detect an address or a postal code in a variable

My questions sound may different but I am really looking for solution. 我的问题听起来可能有所不同,但我确实正在寻找解决方案。

I have a variable in PHP, let's say $check , containing a string. 我在PHP中有一个变量,比如说$check ,包含一个字符串。 It can be either an address or a postal code. 它可以是地址或邮政编码。 Is there any rule we can apply here to check whether variable has postcode or address? 我们可以在这里应用任何规则来检查变量是否具有邮政编码或地址吗?

Edit: This website is for UK 编辑:这个网站是英国的

Thanks 谢谢

Quite detailed link: here 相当详细的链接: 这里

function IsPostcode($postcode)
    {
    $postcode = strtoupper(str_replace(' ','',$postcode));
    if(preg_match("/^[A-Z]{1,2}[0-9]{2,3}[A-Z]{2}$/",$postcode) || preg_match("/^[A-Z]{1,2}[0-9]{1}[A-Z]{1}[0-9]{1}[A-Z]{2}$/",$postcode) || preg_match("/^GIR0[A-Z]{2}$/",$postcode))
    return true;
    else
    return false;
    }

Use: 采用:

$e = "AB235RB";
if (IsPostcode($e))
print "Valid Post Code";
else
print "Invalid Post Code";

I have written a UK postcode validator based off this, so I know it works :) 我已经基于此编写了英国邮政编码验证器,因此我知道它是可行的:)

New Answer 新答案

As Marc B pointed out, my initial answer will not work due to the alphanumeric quality of UK zipcodes. 正如Marc B所指出的,由于英国邮政编码的字母数字质量,我的最初答案将无效。 In that case, I suggest preg_match to regex match the zipcode, or you could do a strlen on $check and look for the length of a zip code if you can be sure no addresses will ever be that length. 在那种情况下,我建议preg_match来使正则表达式匹配邮政编码,或者如果您可以确定没有地址会是该长度,则可以对$check做一个strlen ,并查找邮政编码的长度。

I'd recommend reading this question for a good discussion on the regex required. 我建议阅读此问题 ,以更好地讨论所需的正则表达式。

Old Answer 旧答案

If it is a simple zip code (ie not like 12345-1234), you could check with is_numeric . 如果它是一个简单的邮政编码(即不喜欢12345-1234),则可以使用is_numeric检查。 That is a bit of a hack, but it may suit your purposes. 这有点骇人听闻,但它可能适合您的目的。 Even if it is a complex zip, you could always use str_replace to remove the - and check is_numeric . 即使它是一个复杂的zip,也可以始终使用str_replace删除-并检查is_numeric This is of course assuming the address has some character/string contents and is not fully numeric. 当然,这是假定地址具有某些字符/字符串内容并且不是全数字的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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