Home > OS >  Detecting alphanumeric id's with regular expressions PHP
Detecting alphanumeric id's with regular expressions PHP

Time:11-19

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
}

?>

CodePudding user response:

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 ^[a-z] [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 */
}
  • Related