<?php

/**
 * PHP Array key exists
 */
$n 100000;

$string 'BGVZUKgstzfg87i86ef6&($%/(798zwefogflwef';
$valid array_merge(range('a','z'),range('0','9'));
foreach(
$valid as $k => $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], $validtrue)) {
            
$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_start3'.''')
    .
" 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_start3'.''')
    .
" 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_start3'.''')
    .
" seconds - cleanString() \n";

?>