Function to return only alpha-numeric characters from string?

Function to return only alpha-numeric characters from string?

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

Stefan Bogdanescu

Founder & Senior Architect

Sanitizing Strings: Alpha-Numeric vs. Alphabetic in PHP

Stripping special characters from user input is a fundamental requirement for data validation, but the specific definition of "safe" varies by context. You often need to isolate pure alphanumeric sequences for database identifiers or usernames, while other scenarios demand strictly alphabetic strings for labels or codes. In PHP, achieving this requires understanding regular expressions and character classes rather than relying on simple string replacement loops, which can be inefficient and error-prone with complex patterns.

The most robust approach for retaining only alpha-numeric characters relies on the preg_replace function combined with a negative lookbehind or simply matching what you want to keep. However, PHP's standard preg_match logic usually works best by matching the unwanted content and removing it, or conversely, matching the desired content and extracting it.

To extract only alpha-numeric characters (A-Z, a-z, 0-9), you can use a regex pattern that specifically targets these sets. The following function iterates over input strings, stripping any character that does not fit the [a-zA-Z0-9] pattern:

function getAlphaNumeric($string) {
    if (empty($string)) {
        return '';
    }
    
    // Remove all characters except letters and numbers
    $cleaned = preg_replace('/[^a-zA-Z0-9]+/', '', $string);
    
    return $cleaned;
}

This implementation uses a character class [^...] which matches anything not inside the brackets. The + quantifier ensures that sequences of special characters are removed in a single pass, preventing them from being re-added if they appear consecutively. This is generally safer than using str_replace in a loop, as it handles edge cases like multiple consecutive spaces or symbols more efficiently.

If your requirement shifts to accepting only alphabetic characters (A-Z and a-z), the pattern must explicitly exclude digits. You can achieve this by adjusting the character class to [a-zA-Z]:

function getAlphaOnly($string) {
    if (empty($string)) {
        return '';
    }
    
    // Remove all characters except letters
    $cleaned = preg_replace('/[^a-zA-Z]+/', '', $string);
    
    return $cleaned;
}

The logic remains identical, but the definition of "valid" has narrowed. This distinction is critical when processing data for specific fields. For example, a product SKU might allow numbers, whereas a category name should not contain numeric suffixes that could break sorting algorithms in legacy systems.

Handling Unicode and Locale Sensitivity

A common pitfall in PHP sanitization functions involves the handling of non-ASCII characters. The patterns above strictly limit output to standard ASCII letters and digits. If your application supports internationalized domain names or user-generated content in languages like Spanish (ñ), German (ü), or Japanese, these strict ASCII constraints will result in significant data loss.

For instance, applying getAlphaNumeric to the string "Café" would return "Cafe". While this might be acceptable for a legacy system expecting ASCII-only storage, it is often undesirable for modern applications requiring Unicode normalization. If you need to preserve accented characters while still stripping special symbols, you must modify the regex to include Unicode property escapes or broaden the character class. In PHP 8.0+, using \p{L} and \p{N} allows matching any letter and number from any language:

function getUnicodeAlphaNumeric($string) {
    return preg_replace('/[^\p{L}\p{N}]+/', '', $string);
}

Using property escapes ensures that "Café" becomes "Café" (or normalized to "Cafe" depending on your database collation settings), preserving the semantic meaning of the input. However, this introduces a dependency on PHP's ICU extensions and requires careful consideration of how your database encodes strings (UTF-8 vs. ASCII).

Performance Considerations

While preg_replace is highly optimized in C, it is worth noting that for extremely high-throughput environments where every microsecond counts, pure string manipulation using strtr or mb_strtolower might be explored. However, regex patterns are generally fast enough for typical web applications and offer superior readability and maintainability.

When implementing these functions, always consider the cost of validation versus storage. If your backend database column is defined as VARCHAR(255) CHAR, storing cleaned alphanumeric data prevents encoding errors later. Conversely, if you store raw input, you risk index corruption or injection vulnerabilities if those special characters have semantic meaning in query languages like SQL.

For projects where strict sanitization policies are mandatory across the entire stack, consider leveraging existing libraries or checking resources from https://laravelcompany.com for best practices on Laravel-specific validation rules that handle these string constraints natively.

Our network