php code to validate alphanumeric string

I want to validate alphanumeric string in form text box in php. It can contain numbers and special characters like '.' and '-' but the string should not contain only numbers and special characters. Please help with the code.

Answers


Try this

// Validate alphanumeric
if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9._]+$/', $input)) {
    // Valid
} else {
    // Invalid
}

Use ctype_alnum like below:

if(ctype_alnum($string)){
    echo "Yes, It's an alphanumeric string/text";
}
else{
    echo "No, It's not an alphanumeric string/text";
}

Read function specification on php.net


Code:

if(preg_match('/[^a-z_\-0-9]/i', $string)) { echo "not valid string"; }

Explanation:

  • [] => character class definition
  • ^ => negate the class
  • a-z => chars from 'a' to 'z'
  • _ => underscore
  • - => hyphen '-' (You need to escape it)
  • 0-9 => numbers (from zero to nine)

The 'i' modifier at the end of the regex is for 'case-insensitive' if you don't put that you will need to add the upper case characters in the code before by doing A-Z


I'm sort of new to regex, but I would do it this way:

preg_match('/^[\w.-]+$/', input)

Need Your Help

Volatile or synchronized for primitive type?

java multithreading atomic volatile synchronized

In Java, assignment is atomic if the size of the variable is less than or equal to 32 bits but is not if more than 32 bits.

Optimise PostgreSQL for fast testing

sql database performance postgresql database-tuning

I am switching to PostgreSQL from SQLite for a typical Rails application.