PHP preg_match - only allow alphanumeric strings and - _ characters

PHP preg_match - only allow alphanumeric strings and - _ characters

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

Stefan Bogdanescu

Founder & Senior Architect

Precise Validation: Allowing Only Alphanumeric, Hyphens, and Underscores in PHP

Validating user input is a critical part of building secure applications. A common requirement is ensuring that an identifier or username adheres to a strict format, allowing only letters, numbers, hyphens, and underscores. The preg_match function in PHP provides the necessary tools for this, but getting the pattern right requires understanding how character classes work and where common pitfalls lie.

The goal is to match strings composed entirely of valid characters while rejecting anything else. Consider a scenario where you have two inputs: one containing invalid symbols like an asterisk, and another using only allowed characters.

$string1 = "This is a string*";
$string2 = "this_is-a-string";

// Pattern explanation follows below
if (preg_match('/^[a-zA-Z0-9_-]+$/', $string1)) {
    echo "String 1 not acceptable"; // Output: String 1 not acceptable will NOT print
} else {
    echo "String 1 contains invalid characters";
}

// For the second string, we need to ensure it's fully valid
if (preg_match('/^[a-zA-Z0-9_-]+$/', $string2)) {
    echo "String 2 is acceptable"; // Output: String 2 is acceptable will print
} else {
    echo "String 2 contains invalid characters";
}

The core of the solution lies in the regular expression pattern /^[a-zA-Z0-9_-]+$/. This pattern uses anchors and character classes to enforce strict boundaries. The ^ at the beginning asserts the start of the string, ensuring no hidden characters or whitespace exist before the first valid character. Conversely, the $ at the end asserts the string terminates immediately after the last valid character. Without these anchors, a pattern like /[a-zA-Z0-9_-]+/ would match "abc" inside "abc123!", which is often not the desired behavior for validation logic.

The character class [a-zA-Z0-9_-] defines the set of permitted characters:

  • a-z and A-Z: Uppercase and lowercase letters.
  • 0-9: Numeric digits.
  • _: Underscore.
  • -: Hyphen.

Placing the hyphen at the end of the character class, before the closing bracket, is a crucial technical detail. Inside square brackets, a hyphen usually denotes a range (e.g., a-z). If you write [a-zA-Z0-9-_], PHP interprets this as a range between underscore and the null character (ASCII 0), which matches nothing useful or potentially unexpected characters depending on locale settings. By moving the hyphen to the end ([_-] or -]) or escaping it (\-), you ensure it is treated literally. In this specific pattern, _- explicitly tells the engine to match either an underscore or a literal hyphen.

One frequent mistake developers make is ignoring case sensitivity. While [a-z] covers lowercase, valid identifiers often require uppercase letters as well (e.g., "My_ID"). The pattern provided above explicitly includes both ranges. If you want to simplify the syntax, PHP supports Unicode properties via pcre extensions in modern versions, but standard ASCII ranges remain the most portable and compatible approach for legacy systems.

Another consideration is the length of the string. The quantifier + requires at least one character. If the input can be empty, you must change this to * (zero or more) or validate the length separately. For instance, an empty string would pass a /^...$/ check with *, but fail with +. Since most identifiers require content, + is usually the safer default choice.

If you are building a larger application using the Laravel framework, you might consider defining this validation rule within your Rules directory or extending the built-in validator. However, for raw PHP scripts or legacy codebases, preg_match remains an efficient, zero-dependency solution. Just remember that regex patterns are static; if business rules change—such as allowing spaces in passwords—you must update both the pattern and the surrounding logic accordingly.

Ultimately, precision in regex prevents subtle bugs where valid data is rejected or invalid data slips through. By anchoring the pattern and correctly placing special characters within the class, you create a robust gatekeeper for your input strings.

Our network