function foo($str, $allowed_values) { return preg_replace('#[^'.$allowed_values.']#', '', $str); } echo foo('=)(009asda', '0-9a-zåäö');