php most efficient way to check if a variable contains only certain chars I have a small function which I regularly use to check if a variable contains only [a-z][0-9] and the special chars '-' and '_'. Currently I'm using the following:

function is_clean($string){
    $pattern = "/([a-z]|[A-Z]|[0-9]|-|_)*/";
    preg_match($pattern, $string, $return);
    $pass = (($string == $return[0]) ? TRUE : FALSE);
    return $pass;
}


1 - Can anyone tell me if this is the best/most efficient way to do this and if not try to explain why?

2 - When I view this function through my IDE I get a warning that $return is uninitialized... should I be initializing variables in advance with php, if so how and why?
No need for all that. Just use one bracket group, negate it (be prepending a ^), and use the return value directly:

function is_clean ($string) {
    return ! preg_match("/[^a-z\d_-]/i", $string);
}




Here's a quote from the PHP docs:


  Return Values
  preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.


In the regex above, we're looking for any characters in the string that are not in the bracket group. If none are found, preg_match will return 0 (which when negated will result in true). If any of those characters are found, 1 will be returned and negated to false.