filter_var

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

Validates or sanitizes a value with a built-in dictionary of filters: the FILTER_VALIDATE_* family validates (false on failure, or null with FILTER_NULL_ON_FAILURE), the FILTER_SANITIZE_* family sanitizes - PHP's unique "validation dictionary" ecosystem.

C C23

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

// C has no validator at all: every check is hand-rolled over raw strings
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; /* host must look like a domain */
    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;
}
Output
true
false
true
false
42
false

C++ C++26

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

// C++ has no validator either: hand-rolled checks over 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;
}
Output
true
false
true
false
42
false

C# v11.0.100

v11.0.100
// C# has no built-in validator: regex + Uri hand-assembled
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);
Output
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 has no built-in validator: stdlib pieces are hand-assembled
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"))
}
Output
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 has no built-in validator: regex + URI hand-assembled
        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);
        }
    }
}
Output
true
false
true
false
42
false

JavaScript v26.13.1

v26.13.1
// JS has no built-in validator: every check is hand-rolled (or a schema library)
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; // "/" only means no real path
    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);
Output
true
false
true
false
42
false

PHP v8.6.0

v8.6.0
// filter_var: one entry point, a whole dictionary of built-in validators
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));
Output
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 has no built-in validator: regex plus urllib, or third-party libs
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"))
Output
True
False
True
False
42
False

Rust v1.99.1

v1.99.1
// Rust has no built-in validator: hand-rolled checks (regex/email need crates in practice)
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; // host must at least look like a domain
    }
    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"),
    }
}
Output
true
false
true
false
42
false

TypeScript v26.13.1

v26.13.1
// TS adds types but still no validator: same hand-rolled checks as 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);
Output
true
false
true
false
42
false

Language differences

C: no built-in validator - is_email etc. are all hand-rolled; POSIX regex.h is the lowest building block.

C++: no built-in validator - hand-rolled over std::string.

C#: no built-in validator - Uri.TryCreate only judges URL shape; email still needs regex.

Go: no built-in validator - net/mail + net/url + strconv hand-assembled.

Java: no built-in validator - URI + matches hand-assembled.

JavaScript: no built-in validator - the demo hand-rolls regexes; real projects reach for schema libraries like zod/ajv.

PHP: validation failure returns false rather than throwing - "0" is a valid integer but falsy, so compare strictly with === false; pair boolean validation with FILTER_NULL_ON_FAILURE to tell "false" apart from "invalid"; since PHP 8.5, FILTER_THROW_ON_FAILURE makes failures throw Filter\FilterFailedException; FILTER_SANITIZE_STRING was removed in 8.5 - use htmlspecialchars to sanitize HTML.

Python: no built-in validator - int() parses directly but regex should constrain the format first; the email-validation ecosystem is the third-party email-validator.

Rust: no built-in validator - regex/validator are third-party crates; only hand-rolling exists in std.

TypeScript: same as JavaScript.

The FILTER_VALIDATE_* family: EMAIL, URL, INT, FLOAT, BOOLEAN, IP, DOMAIN, REGEXP, MAC.