PHP - regex to allow letters and numbers only

PHP - regex to allow letters and numbers only

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Regex Patterns for Validating Alphanumeric Input in PHP

When validating user input in PHP, the most common request involves ensuring a string contains only letters and numbers. A frequent stumbling block occurs when developers attempt to use preg_match but fail to account for how regular expression quantifiers work. Consider the snippet provided in typical troubleshooting scenarios:

preg_match("/^[a-zA-Z0-9]", $value)

This pattern attempts to match the start of a string (^) followed by exactly one character from the set a-z, A-Z, or 0-9. While this technically validates that the first character is alphanumeric, it does not prevent additional characters from following. Consequently, passing "abc123" would return true even if your business logic requires a strictly single-character input, or conversely, failing to reject strings like "abc123!" properly because the regex engine stops matching after finding the first valid character and ignores the rest unless you explicitly tell it what to do next.

To enforce that an entire string consists only of alphanumeric characters, you must anchor the pattern at both the start and the end of the string. In PCRE (the flavor used by PHP), this is achieved using the ^ anchor for the beginning and $ for the end. Without the trailing $, the regex engine treats the match as successful as soon as it finds a valid character, effectively making the pattern permissive rather than restrictive.

Here is the corrected approach for validating that a string contains exclusively letters and numbers:

if (preg_match('/^[a-zA-Z0-9]+$/', $value)) {
    // The string is valid
} else {
    // The string contains invalid characters or is empty
}

The $ anchor ensures the engine checks every character in the input. If it encounters a symbol, space, or special character before reaching the end of the string, preg_match returns false immediately. Additionally, note that the pattern does not include the + quantifier in the original failing example. The + means "one or more" characters. If you omit the +, the pattern technically matches an empty string as valid (matching zero instances of the character class) depending on how strictly you define your requirements, though usually, you want to reject empty inputs.

Handling Unicode and Case Sensitivity

Strictly listing [a-zA-Z] works for standard ASCII characters but ignores accented letters found in many European languages (e.g., é, ñ, ü). If your application serves a global audience, relying on a hardcoded ASCII range might lead to poor user experience. PHP provides the \p{L} modifier within character classes to match any Unicode letter, and \p{N} for any number.

However, using Unicode properties requires enabling the u flag in your pattern. Without this flag, \p{L} will not function as expected and might only match ASCII letters depending on the PHP version and PCRE settings. A more robust pattern for international alphanumeric input looks like this:

preg_match('/^\p{L}\p{N}+$/', $value, null, PREG_UNMATCHED_AS_NULL | PREG_UTF8);
// Actually simpler with the u flag:
preg_match('/^\p{L}+\p{N}*$/', $value, null, PREG_UTF8);

Wait, that logic is getting complex. Let's simplify. To match any Unicode letter or number one or more times, the pattern should be /^\p{L}\p{N}+$/u. Actually, to allow a mix of letters and numbers freely, you simply use the character class union: [\p{L}\p{N}]+.

if (preg_match('/^[\p{L}\p{N}]+$/', $value)) {
    // Valid Unicode alphanumeric string
}

Performance Considerations

While [a-zA-Z0-9] is faster because it avoids the overhead of Unicode property lookups, the performance difference is usually negligible for simple validation checks. The primary trade-off here is inclusivity versus speed. If you are processing millions of records per second in a high-throughput API endpoint, optimizing the character class to [a-zA-Z0-9] reduces CPU cycles slightly. For application logic or forms where user experience matters more than micro-optimizations, supporting Unicode via the u flag is the preferred engineering decision.

Integration with Laravel

If you are working within the Laravel ecosystem, while native PHP regex works perfectly fine, leveraging built-in validation rules can make your code more readable and maintainable. Laravel's validator engine handles these checks internally, abstracting away the regex complexity until you need to customize it. You might find resources discussing advanced validation patterns at https://laravelcompany.com if you need help extending those rules for specific custom formats. However, understanding the underlying regex mechanics remains essential when you encounter edge cases that the standard Rule classes do not cover out of the box.

Ultimately, the distinction between matching a character and validating an entire string is the critical concept to internalize. Always remember to anchor your patterns with ^ and $, and use quantifiers like + to ensure you are validating the whole input payload, not just its first byte.

Our network