PHP 正则后瞻 匹配是否是域名,准确率99.99%

来源:互联网 发布:天津天狮网络主打歌曲 编辑:程序博客网 时间:2024/05/16 15:57
/^([a-z0-9]+([a-z0-9-]*(?:[a-z0-9]+))?\.)?[a-z0-9]+([a-z0-9-]*(?:[a-z0-9]+))?(\.us|\.tv|\.org\.cn|\.org|\.net\.cn|\.net|\.mobi|\.me|\.la|\.info|\.hk|\.gov\.cn|\.edu|\.com\.cn|\.com|\.co\.jp|\.co|\.cn|\.cc|\.biz)$/i

匹配网址:

    /**     * @author      Default7 <default7@zbphp.com>     * @description 匹配     *              t.cn 正确     *              t-.cn 错误     *              tt.cn正确     *              -t.cn 错误     *              t-t.cn 正确     *              tst-test-tst.cn 正确     *              tst--tt.cn -- 错误     *     *     *     * @param $domain     *     * @return bool     */    public function isDomain($domain)    {        return !empty($domain) && strpos($domain, '--') === false &&        preg_match('/^([a-z0-9]+([a-z0-9-]*(?:[a-z0-9]+))?\.)?[a-z0-9]+([a-z0-9-]*(?:[a-z0-9]+))?(\.us|\.tv|\.org\.cn|\.org|\.net\.cn|\.net|\.mobi|\.me|\.la|\.info|\.hk|\.gov\.cn|\.edu|\.com\.cn|\.com|\.co\.jp|\.co|\.cn|\.cc|\.biz)$/i', $domain) ? true : false;    }
如果有问题bug,欢迎指正 by default7#zbphp.com

第二种写法:

    /**     * @param string $str     *     * @return bool     */    public static function isDomain($str = '')    {        return !empty($str) && !preg_match('/^-|-$|--|-\.|\.-/', $str) && preg_match('/^([\w-]+\.)?[\w-]+' . self::RegExpSuffix() . '$/', $str) ? true : false;//        return !empty($str) && strpos($str, '--') === false && preg_match('/^(([a-z0-9]+([a-z0-9-]*(?:[a-z0-9]+))?\.)?[a-z0-9]+([a-z0-9-]*(?:[a-z0-9]+))?' . self::RegExpSuffix() . ')$/i', $str) ? true : false;    }    /**     * @return mixed     */    public static function RegExpSuffix()    {        return '(' . str_replace('.', '\.', implode('|', self::allowDomainSuffix())) . ')';    }    /**     * @description 允许的扩展名     * @return array     */    public static function allowDomainSuffix()    {        $arr = array(            '.com',            '.com.cn',            '.cn',            '.net',            '.net.cn',            '.org',            '.org.cn',            '.gov.cn',            '.hk',            '.cc',            '.info',            '.biz',            '.mobi',            '.us',            '.me',            '.co',            '.co.jp',            '.edu',            '.tv',            '.la',        );        sort($arr);        return array_unique(array_reverse($arr));    }


0 0