Current Location: Home> Latest Articles> PHP Guide: How to Check if Input Contains Only Letters and Numbers

PHP Guide: How to Check if Input Contains Only Letters and Numbers

M66 2025-10-09

The Importance of Input Validation in PHP

In PHP development, validating user input is a crucial step to ensure the security of your application. If an input contains special characters or symbols, it can lead to security risks such as SQL injection or XSS attacks. To avoid these issues, developers often restrict input formats — for example, allowing only letters and numbers.

Using Regular Expressions for Validation

PHP provides powerful regular expression functions that make it easy to verify whether a string contains only letters and numbers. Regular expressions are one of the most effective tools for input validation.

Here’s a simple PHP function that checks if the input contains only letters and numbers:

function isAlphaNumeric($input){
    return preg_match('/^[A-Za-z0-9]+$/', $input);
}

This function uses the preg_match() function to test the input against the regular expression /^[A-Za-z0-9]+$/. Here’s what each part means:

  • ^ — indicates the start of the string
  • [A-Za-z0-9]+ — matches one or more uppercase letters, lowercase letters, or digits
  • $ — indicates the end of the string

In other words, this expression ensures that the entire string contains only letters or numbers.

Full Example Code

Here’s a complete example showing how to use the function to validate user input:

$input1 = "abc123";  // valid input
$input2 = "abc@123";  // invalid input

if(isAlphaNumeric($input1)){
    echo "Input 1 contains only letters and numbers";
}else{
    echo "Input 1 contains invalid characters";
}

if(isAlphaNumeric($input2)){
    echo "Input 2 contains only letters and numbers";
}else{
    echo "Input 2 contains invalid characters";
}

The output will be:

  • Input 1: “Input 1 contains only letters and numbers”
  • Input 2: “Input 2 contains invalid characters”

This example shows how regular expressions provide a simple and effective way to validate input, making them ideal for fields like usernames, passwords, or IDs.

Conclusion

In PHP development, input validation plays a vital role in preventing security vulnerabilities and maintaining code reliability. This article demonstrated how to use a regular expression to check whether an input contains only letters and numbers, along with a practical example. Mastering this technique will help you handle user input securely and confidently in your projects.