简体   繁体   中英

Detecting alphanumeric id's with regular expressions PHP

I'm trying to detect if a string in an array is only an alphanumeric id with PHP. In this case, "Dog", "bird", and "cat" should not evaluated to false. How would this be achieved with a regular expression?

<?php

$array = array("Dog", "g60878", "bird", "d3308043", "r797717830", "cat", "oa30");

foreach($array as $string){
    //if $string matches an alphanumeric id regex, echo $string
}

?>

This would be possible with [0-9a-zA-Z]+ .

In PHP you can use:

if(preg_match("/^[0-9a-z]+$/i", $string) == 1) {
    /* true */
}

The small i makes the testing case insensitive, therefore you can ignore capital letters in the regular expression. The delimiters ^ and $ represent the start and the end of the string and are used here to make sure that the whole string only consists of valid characters.


Edit due to clarification of the question

You cannot use regex to test against randomness, since you would need a dictionary for this. But it seems that the pattern of the strings you want to let pass the test is that they start with one or more lower case letters, followed by one or more digts. If this is indeed the pattern, you can test against ^[az]+[0-9]+$ .

If you only want strings with lower case letters to pass, you need to omit the i in the regex string used in the above mentioned PHP function. So maybe what could work for you is

if(preg_match("/^[a-z]+[0-9]+$/", $string) == 1) {
    /* true */
}

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