Skip to content

Instantly share code, notes, and snippets.

@uu59
Created April 13, 2012 10:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save uu59/2375573 to your computer and use it in GitHub Desktop.
Save uu59/2375573 to your computer and use it in GitHub Desktop.
filter_var vs. preg_match
<?php
// http://nob-log.info/2012/04/12/phper-filter-validate-email/
$times = 10000;
$result = array();
// preg_match
// regexp is stolen from:
// https://github.com/php/php-src/blob/master/ext/filter/logical_filters.c#L525
$regexp = "/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD";
$start_m = microtime();
$start = time();
for ($i=0; $i < $times; $i++){
preg_match($regexp, 'bob@example.com');
}
$end_m = microtime();
$end = time();
$bench = ($end - $start) + ($end_m - $start_m);
$result["preg_match"] = $bench;
// filter_var
$start_m = microtime();
$start = time();
for ($i=0; $i < $times; $i++){
filter_var('bob@example.com', FILTER_VALIDATE_EMAIL);
}
$end_m = microtime();
$end = time();
$bench = ($end - $start) + ($end_m - $start_m);
$result["filter_var"] = $bench;
var_dump(array(
"times" => $times,
"results" => $result
));
// my result is:
//
//
// PHP 5.3.4 (cli) (built: Dec 15 2010 12:15:07)
// Copyright (c) 1997-2010 The PHP Group
// Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
//
// array(2) {
// ["times"]=>
// int(10000)
// ["results"]=>
// array(2) {
// ["preg_match"]=>
// float(0.200819)
// ["filter_var"]=>
// float(0.201253)
// }
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment