简体   繁体   中英

How to validate letter & number or only letter strings?

I want to match letters and numbers, but not only numbers.

So I want to create a preg_match() pattern to filter like this:

eg:

  1. no123 true
  2. 123no true
  3. 123456 false
  4. letters true

Using a SKIP-FAIL pattern will outperform Toto's pattern (and MH2K9's answer is incorrect as it doesn't allow all alphabetical matches). You can test their patterns on the sample text in my demo link.

/^\\d+$(*SKIP)(*FAIL)|^[az\\d]+$/i

Pattern Demo Link

This "disqualifies" purely numeric strings, and matches mixed (numeric-alphabetical) and purely alphabetical strings.

Code: ( Demo )

$string='test123';
var_export(preg_match('/^\d+$(*SKIP)(*FAIL)|^[a-z\d]+$/i',$string)?true:false);

Output:

true

UPDATE: Regular expressions aside, this task logic can be performed by two very simple non-regex calls: ctype_alnum() and ctype_digit()

Code: ( Demo )

$tests = [
    'no123', // true
    '123no', // true
    '123456', // false
    'letters', // true
];

foreach ($tests as $test) {
    echo "$test evaluates as " , (ctype_alnum($test) && !ctype_digit($test) ? 'true' : 'false') , "\n";
}

Output:

no123 evaluates as true
123no evaluates as true
123456 evaluates as false
letters evaluates as true

So we must have at least one letter. There can be any amount of digits before it and any amount of alphanumeric characters is allowed until end of the string.

/^\d*[a-z][a-z\d]*$/i
  • ^ start of string
  • \\d* any amount of digits
  • [az] one letter
  • [az\\d]* any amount of alphanumeric characters
  • $ until end of the string
  • i flag for caseless matching

See this demo at regex101

You can try this Regex . It checks both number and letter at least one.

(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$

According to your comment: "only letters vaild but only number invalid.", this wil do the job:

if (preg_match('/^(?=.*[a-z])[a-z0-9]+$/i', $inputString)) {
    // valid
} else {
    // invalid
}

Explanation:

/               : regex delimiter
  ^             : start of string
    (?=.*[a-z]) : lookahead, make sure we have at least one letter
    [a-z0-9]+   : string contains only letters and numbers
  $             : end of string
/i              : regex delimiter + flag case insensitive

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM