filter_var

filter_var(mixed $value, int $filter = FILTER_DEFAULT, array|int $options = 0): mixed

用内建过滤器字典校验或净化一个值:FILTER_VALIDATE_* 家族校验(失败返回 false,可换 FILTER_NULL_ON_FAILURE 返回 null),FILTER_SANITIZE_* 家族净化。PHP 独有的「校验字典」生态。

C C23

C23
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// C 完全没有校验器:每个检查都在原始字符串上手写
static bool is_email(const char *s) {
    const char *at = strchr(s, '@');
    return at != NULL && at != s && strchr(at + 1, '.') != NULL && strchr(s, ' ') == NULL;
}

static bool is_http_url(const char *s, bool need_path) {
    const char *p = strstr(s, "://");
    if (p == NULL) return false;
    bool http = strncmp(s, "http://", 7) == 0 || strncmp(s, "https://", 8) == 0;
    if (!http) return false;
    const char *after = p + 3;
    if (strchr(after, '.') == NULL) return false; /* 主机必须像个域名 */
    if (!need_path) return true;
    const char *slash = strchr(after, '/');
    return slash != NULL && slash[1] != '\0';
}

static bool validate_int(const char *s, long *out) {
    if (*s == '\0') return false;
    char *end = NULL;
    long v = strtol(s, &end, 10);
    if (end == s || *end != '\0') return false;
    *out = v;
    return true;
}

int main(void) {
    printf("%s\n", is_email("bob@example.com") ? "true" : "false");
    printf("%s\n", is_email("not an email") ? "true" : "false");
    printf("%s\n", is_http_url("https://example.com/path", false) ? "true" : "false");
    printf("%s\n", is_http_url("https://example.com", true) ? "true" : "false");
    long n = 0;
    if (validate_int("42", &n)) printf("%ld\n", n); else printf("false\n");
    if (validate_int("4.2", &n)) printf("%ld\n", n); else printf("false\n");
    return 0;
}
输出
true
false
true
false
42
false

C++ C++26

C++26
#include <iostream>
#include <string>

// C++ 也没有校验器:在 std::string 上手写检查
static bool isEmail(const std::string &s) {
    auto at = s.find('@');
    return at != std::string::npos && at != 0
        && s.find('.', at) != std::string::npos
        && s.find(' ') == std::string::npos;
}

static bool isHttpUrl(const std::string &s, bool needPath) {
    auto pos = s.find("://");
    if (pos == std::string::npos) return false;
    if (s.rfind("http://", 0) != 0 && s.rfind("https://", 0) != 0) return false;
    std::string after = s.substr(pos + 3);
    if (after.find('.') == std::string::npos) return false;
    if (!needPath) return true;
    auto slash = after.find('/');
    return slash != std::string::npos && slash + 1 < after.size();
}

static bool validateInt(const std::string &s, long &out) {
    try {
        size_t used = 0;
        out = std::stol(s, &used);
        return used == s.size();
    } catch (...) {
        return false;
    }
}

int main() {
    std::cout << (isEmail("bob@example.com") ? "true" : "false") << "\n";
    std::cout << (isEmail("not an email") ? "true" : "false") << "\n";
    std::cout << (isHttpUrl("https://example.com/path", false) ? "true" : "false") << "\n";
    std::cout << (isHttpUrl("https://example.com", true) ? "true" : "false") << "\n";
    long n = 0;
    if (validateInt("42", n)) std::cout << n << "\n"; else std::cout << "false\n";
    if (validateInt("4.2", n)) std::cout << n << "\n"; else std::cout << "false\n";
    return 0;
}
输出
true
false
true
false
42
false

C# v11.0.100

v11.0.100
// C# 没有内建校验器:正则 + Uri 手工拼装
using System.Text.RegularExpressions;

bool IsEmail(string s) => Regex.IsMatch(s, @"^[^@\s]+@[^@\s]+\.[^@\s]+$");

bool IsHttpUrl(string s, bool needPath) {
    if (!Uri.TryCreate(s, UriKind.Absolute, out Uri? u)) return false;
    if (u.Scheme != Uri.UriSchemeHttp && u.Scheme != Uri.UriSchemeHttps) return false;
    return !needPath || u.AbsolutePath.Trim('/').Length > 0;
}

Console.WriteLine(IsEmail("bob@example.com"));
Console.WriteLine(IsEmail("not an email"));
Console.WriteLine(IsHttpUrl("https://example.com/path", false));
Console.WriteLine(IsHttpUrl("https://example.com", true));
if (int.TryParse("42", out int n)) Console.WriteLine(n); else Console.WriteLine(false);
if (int.TryParse("4.2", out n)) Console.WriteLine(n); else Console.WriteLine(false);
输出
True
False
True
False
42
False

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"net/mail"
	"net/url"
	"regexp"
	"strconv"
)

var intRe = regexp.MustCompile(`^[+-]?\d+$`)

// Go 没有内建校验器:拿标准库零件手工拼装
func validateInt(s string) any {
	if !intRe.MatchString(s) {
		return false
	}
	n, err := strconv.Atoi(s)
	if err != nil {
		return false
	}
	return n
}

func main() {
	_, err := mail.ParseAddress("bob@example.com")
	fmt.Println(err == nil)
	_, err = mail.ParseAddress("not an email")
	fmt.Println(err == nil)

	u, err := url.Parse("https://example.com/path")
	fmt.Println(err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Host != "")
	u, err = url.Parse("https://example.com")
	fmt.Println(err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Host != "" && u.Path != "")

	fmt.Println(validateInt("42"))
	fmt.Println(validateInt("4.2"))
}
输出
true
false
true
false
42
false

Java v27.0.1

v27.0.1
public class Main {
    static boolean isEmail(String s) {
        return s.matches("^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$");
    }
    static boolean isHttpUrl(String s, boolean needPath) {
        try {
            java.net.URI u = new java.net.URI(s);
            boolean http = u.getScheme() != null
                && (u.getScheme().equals("http") || u.getScheme().equals("https"));
            if (!http || u.getHost() == null) return false;
            return !needPath || (u.getPath() != null && !u.getPath().isEmpty());
        } catch (java.net.URISyntaxException e) {
            return false;
        }
    }
    public static void main(String[] args) {
        // Java 没有内建校验器:正则 + URI 手工拼装
        System.out.println(isEmail("bob@example.com"));
        System.out.println(isEmail("not an email"));
        System.out.println(isHttpUrl("https://example.com/path", false));
        System.out.println(isHttpUrl("https://example.com", true));
        try {
            System.out.println(Integer.parseInt("42"));
        } catch (NumberFormatException e) {
            System.out.println(false);
        }
        try {
            System.out.println(Integer.parseInt("4.2"));
        } catch (NumberFormatException e) {
            System.out.println(false);
        }
    }
}
输出
true
false
true
false
42
false

JavaScript v26.13.1

v26.13.1
// JS 没有内建校验器:每个检查都得手写(或借助 schema 库)
const emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const intRe = /^[+-]?\d+$/;
const parseHttpUrl = (s, needPath) => {
  try {
    const u = new URL(s);
    if (u.protocol !== "http:" && u.protocol !== "https:") return false;
    if (needPath && u.pathname === "/") return false; // "/" 只表示没有真实路径
    return true;
  } catch {
    return false;
  }
};
console.log(emailRe.test("bob@example.com"));
console.log(emailRe.test("not an email"));
console.log(parseHttpUrl("https://example.com/path", false));
console.log(parseHttpUrl("https://example.com", true));
console.log(intRe.test("42") ? parseInt("42", 10) : false);
console.log(intRe.test("4.2") ? parseInt("4.2", 10) : false);
输出
true
false
true
false
42
false

PHP v8.6.0

v8.6.0
// filter_var:一个入口,一整套内建校验器字典
var_dump(filter_var("bob@example.com", FILTER_VALIDATE_EMAIL));
var_dump(filter_var("not an email", FILTER_VALIDATE_EMAIL));
var_dump(filter_var("https://example.com/path", FILTER_VALIDATE_URL));
var_dump(filter_var("https://example.com", FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED));
var_dump(filter_var("42", FILTER_VALIDATE_INT));
var_dump(filter_var("4.2", FILTER_VALIDATE_INT));
输出
string(15) "bob@example.com"
bool(false)
string(24) "https://example.com/path"
bool(false)
int(42)
bool(false)

Python v3.15.2

v3.15.2
# Python 没有内建校验器:正则加 urllib,或第三方库
import re
from urllib.parse import urlparse
def is_email(s):
    return re.fullmatch(r"[^\s@]+@[^\s@]+\.[^\s@]+", s) is not None
def is_http_url(s, need_path=False):
    try:
        p = urlparse(s)
    except ValueError:
        return False
    if p.scheme not in ("http", "https") or not p.netloc:
        return False
    return bool(p.path) if need_path else True
def validate_int(s):
    return int(s) if re.fullmatch(r"[+-]?\d+", s) else False
print(is_email("bob@example.com"))
print(is_email("not an email"))
print(is_http_url("https://example.com/path"))
print(is_http_url("https://example.com", need_path=True))
print(validate_int("42"))
print(validate_int("4.2"))
输出
True
False
True
False
42
False

Rust v1.99.1

v1.99.1
// Rust 没有内建校验器:手写检查(实际项目正则/邮箱需要 crate)
fn is_email(s: &str) -> bool {
    let mut parts = s.split('@');
    match (parts.next(), parts.next(), parts.next()) {
        (Some(local), Some(domain), None) => {
            !local.is_empty()
                && !local.contains(char::is_whitespace)
                && domain.contains('.')
                && !domain.starts_with('.')
                && !domain.ends_with('.')
                && !domain.contains(char::is_whitespace)
        }
        _ => false,
    }
}

fn is_http_url(s: &str, need_path: bool) -> bool {
    let (scheme, rest) = match s.split_once("://") {
        Some(t) => t,
        None => return false,
    };
    if scheme != "http" && scheme != "https" {
        return false;
    }
    let authority_and_path = rest.split(['?', '#']).next().unwrap_or("");
    if !authority_and_path.contains('.') {
        return false; // 主机至少要像个域名
    }
    let after_host = authority_and_path.split('/').skip(1).collect::<Vec<_>>().join("/");
    !need_path || !after_host.is_empty()
}

fn validate_int(s: &str) -> Result<i64, ()> {
    let digits = s.strip_prefix(['+', '-']).unwrap_or(s);
    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
        return Err(());
    }
    s.parse::<i64>().map_err(|_| ())
}

fn main() {
    println!("{}", is_email("bob@example.com"));
    println!("{}", is_email("not an email"));
    println!("{}", is_http_url("https://example.com/path", false));
    println!("{}", is_http_url("https://example.com", true));
    match validate_int("42") {
        Ok(n) => println!("{}", n),
        Err(_) => println!("false"),
    }
    match validate_int("4.2") {
        Ok(n) => println!("{}", n),
        Err(_) => println!("false"),
    }
}
输出
true
false
true
false
42
false

TypeScript v26.13.1

v26.13.1
// TS 加了类型但仍无校验器:与 JS 一样手写检查
const emailRe: RegExp = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const intRe: RegExp = /^[+-]?\d+$/;
const parseHttpUrl = (s: string, needPath: boolean): boolean => {
  try {
    const u: URL = new URL(s);
    if (u.protocol !== "http:" && u.protocol !== "https:") return false;
    if (needPath && u.pathname === "/") return false;
    return true;
  } catch {
    return false;
  }
};
console.log(emailRe.test("bob@example.com"));
console.log(emailRe.test("not an email"));
console.log(parseHttpUrl("https://example.com/path", false));
console.log(parseHttpUrl("https://example.com", true));
console.log(intRe.test("42") ? parseInt("42", 10) : false);
console.log(intRe.test("4.2") ? parseInt("4.2", 10) : false);
输出
true
false
true
false
42
false

语言差异说明

C:无内建校验,is_email 等全部手写;POSIX regex.h 是最低层积木。

C++:无内建校验,在 std::string 上手写。

C#:无内建校验,Uri.TryCreate 只能判 URL 形态,邮箱仍靠正则。

Go:无内建校验,net/mail + net/url + strconv 手工拼装。

Java:无内建校验,URI + matches 手工拼装。

JavaScript:无内建校验,示例手写正则;生产项目多用 zod/ajv 等 schema 库。

PHP:校验失败返回 false 而非抛错——"0" 是合法整数但为假值,必须用 === false 严格比较;布尔校验配 FILTER_NULL_ON_FAILURE 区分「假」与「非法」;PHP 8.5 起 FILTER_THROW_ON_FAILURE 让失败改抛 Filter\FilterFailedException;FILTER_SANITIZE_STRING 已在 8.5 移除,净化 HTML 请用 htmlspecialchars。

Python:无内建校验;int() 可直接解析但需先用正则约束格式;邮箱校验生态是第三方 email-validator。

Rust:无内建校验;regex/validator 等是第三方 crate,标准库只有手写。

TypeScript:同 JavaScript。

FILTER_VALIDATE_* 家族:EMAIL、URL、INT、FLOAT、BOOLEAN、IP、DOMAIN、REGEXP、MAC。