$v) { $valid[$k] = (string)$v; } echo "Test: Rebuilding preg_replace function:\n\n"; // Validating functions echo cleanString($valid, $string); echo "\nshould be the same like:\n"; echo preg_replace('@[^a-z0-9]@', '', $string); echo "\n\n"; // preg_replace replacement /** * Replaces every char in $str that does is not in $valid array * * @param array $valid * @param string $str * @return string */ function cleanString($valid, $str) { $ret = ''; $len = strlen($str); for($i = 0; $i < $len; ++$i) { if(in_array($str[$i], $valid, true)) { $ret .= $str[$i]; } } return $ret; } // Capsuled preg_replace function preg_cleanString($str) { return preg_replace('@[^a-z0-9]@', '', $str); } // Testing pure preg_replace $time_start = microtime(true); $i = 0; while($i++ < $n){ preg_replace('@[^a-z0-9]@', '', $string); } $time_end = microtime(true); echo number_format($time_end-$time_start, 3, '.', '') ." seconds - preg_replace() \n"; // Testing capsuled preg_replace $time_start = microtime(true); $i = 0; while($i++ < $n){ preg_cleanString($string); } $time_end = microtime(true); echo number_format($time_end-$time_start, 3, '.', '') ." seconds - preg_cleanString() \n"; // Testing own function $time_start = microtime(true); $i = 0; while($i++ < $n){ cleanString($valid, $string); } $time_end = microtime(true); echo number_format($time_end-$time_start, 3, '.', '') ." seconds - cleanString() \n"; ?>