开发者

PHP validate input alphanumeric plus a few symbols

开发者 https://www.devze.com 2022-12-20 15:26 出处:网络
Need a way to validate an input field (in PHP) so it can contain only the following: Any letter Any number

Need a way to validate an input field (in PHP) so it can contain only the following:

  • Any letter
  • Any number
  • any of these symbols: - (dash) _ (underscore) @ (at) . (dot) or a SPACE

Field can start or end with any of these (but not a space, but I can trim it before passing into validation function), and contain none, one, or any number (so just a check to make sure everything in the input is one of the above).

I would like to be able to do something like this:

funcion is_valid ( $in_form_input ) {
  // returns true or false
}

if ( is_valid($_POST['field1']) ) {
  echo "valid开发者_如何学运维";
} else {
  echo "not valid";
}


return !preg_match('/[^-_@. 0-9A-Za-z]/', $in_form_input);


Use preg_match():

if (preg_match('!^[\w @.-]*$!', $input)) {
  // its valid
}

Note: \w is synonymous to [a-zA-Z0-9_].


The Best way would be to use like this :-

$str = "";
function validate_username($str) 
{
    $allowed = array(".", "-", "_", "@", " "); // you can add here more value, you want to allow.
    if(ctype_alnum(str_replace($allowed, '', $str ))) {
        return $str;
    } else {
        $str = "Invalid Username";
        return $str;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号