Validating Strings as Alphanumeric Using Regex in PHP
To validate alphanumeric characters using regular expressions, use ^[a-zA-Z0-9]+$. This regular expression matches strings composed of one or more alphanumeric characters, such as "3DModel".
If you want to specify a fixed length of alphanumeric characters, use ^[a-zA-Z0-9]{n}$. For example, to match exactly 6 characters, use ^[a-zA-Z0-9]{6}$. Similarly, you can create flexible patterns by specifying minimum and maximum lengths. For instance, ^[a-zA-Z0-9]{12,20}$ is effective for matching strings between 12 and 20 characters.
Below is a summary of commonly used regular expression patterns. Feel free to use them as needed.
| # | Match Condition | Regular Expression Pattern | 
|---|---|---|
| 1 | Contains only alphanumeric characters | ^[a-zA-Z0-9]+$ | 
| 2 | Fixed length of n alphanumeric characters | ^[a-zA-Z0-9]{n}$ | 
| 3 | At least n alphanumeric characters | ^[a-zA-Z0-9]{n,}$ | 
| 4 | No more than m alphanumeric characters | ^[a-zA-Z0-9]{1,m}$ | 
| 5 | Between n and m alphanumeric characters | ^[a-zA-Z0-9]{n,m}$ | 
Source Code
Below is a PHP function to validate if a given string consists only of alphanumeric characters. The function allows validation based on the following conditions:
- If the minimum length is omitted: Validates that the string is within the specified maximum length and consists only of alphanumeric characters.
- If the maximum length is omitted: Validates that the string meets the minimum length requirement and consists only of alphanumeric characters.
- If both minimum and maximum lengths are omitted: Validates that the string entirely consists of alphanumeric characters.
/**
 * Checks whether a given string consists only of alphanumeric characters.
 *
 * @param string $str The input string.
 * @param ?int $minLength The minimum number of characters (treated as 1 if null).
 * @param ?int $maxLength The maximum number of characters (treated as the length of the string if null).
 * @return bool Returns true if the input string meets the conditions; otherwise, returns false.
 * @throws InvalidArgumentException Throws an exception if the minimum length is less than 1,
 * or if the maximum length is less than the minimum length.
 */
function isAlphanumeric(string $str, ?int $minLength = null, ?int $maxLength = null): bool {
    // Set default values
    $min = $minLength ?? 1;
    $max = $maxLength ?? mb_strlen($str);
    // Validate arguments
    if ($min < 1) {
        // Throw an exception if the minimum length is less than 1
        throw new InvalidArgumentException('The minimum length must be an integer greater than or equal to 1.');
    }
    if (!is_null($maxLength) && $max < $min) {
        // Throw an exception if the maximum length is less than the minimum length
        throw new InvalidArgumentException('The minimum length must not exceed the maximum length.');
    }
    // Construct the regular expression pattern for alphanumeric characters
    $pattern = is_null($maxLength)
        ? sprintf('/^[a-zA-Z0-9]{%d,}$/', (int)$min) // No limit on the maximum number of characters
        : sprintf('/^[a-zA-Z0-9]{%d,%d}$/', (int)$min, (int)$max);
    // Perform the validation using regular expressions
    return (bool)preg_match($pattern, $str);
}
Validation
Specify the range in terms of characters (not bytes).




