/** * 验证域名是否合法 * @param string $domain * @return bool */ function verify_domain(string $domain): bool { $res = "/^(?=^.{3,255}$)(http(s)?:\/\/)(www\.)?[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+(:\d+)*(\/\w+\.\w+)*$/"; if (preg_match($res, $domain)) return true; else return false; }
测试
var_dump(verify_domain('http://code.cent123.com/')); //bool(false) var_dump(verify_domain('http://code.cent123.com')); //bool(true) var_dump(verify_domain('http://www.code.cent123.com')); //bool(true) var_dump(verify_domain('http://code.cent123.com/view/1')); //bool(false) var_dump(verify_domain('code.cent123.com')); //bool(false) var_dump(verify_domain('code.cent123.com')); //bool(false)