Chetan Ameta February 2016

Check input contains either pure numeric characters or pure alpha character using single regular expression

I have a function which will return true if input is pure numeric or alphabate else it will return false. This function is working fine.

function checktype($a)
{
    if (preg_match('/^\d+$/', $a)) { //check numeric (can use other numeric regex also like /^[0-9]+$/ etc)
        $return = true;
    } else if (preg_match('/^[a-zA-Z]+$/', $a)) { //check alphabates
        $return = true;
    } else { //others
        $return = false;
    }
    return $return;
}

var_dump(checktype('abcdfekjh')); //bool(true)
var_dump(checktype('1324654')); //bool(true)
var_dump(checktype('1324654hkjhkjh'));//bool(false)

No I tried to optimized this function by removing conditions so I modified code to:

function checktype($a)
{
    $return  = (preg_match('/^\d+$/', $a) || preg_match('/^[a-zA-Z]+$/', $a)) ? true:false;
    return $return;
}

var_dump(checktype('abcdfekjh')); //bool(true)
var_dump(checktype('1324654')); //bool(true)
var_dump(checktype('1324654hkjhkjh'));//bool(false)

Now in third step I tried to merge both regex in single regex so I can avoid two preg_match function and got stuck here:

function checktype($a)
{
    return (preg_match('regex to check either numeric or alphabates', $a)) ? true:false;
}

I tried a lot of combinations since 2 days by using OR(!) operator using not operator(?!) but no success at all.

Below some reference website from which i pick expression and made some combinations:

http://regexlib.com/UserPatterns.aspx?authorid=26c277f9-61b2-4bf5-bb70-106880138842

http://www.rexegg.com/regex-conditionals.html

OR condition in Reg

Answers


Wiktor Stribi┼╝ew February 2016

A one regex to check if a string is all ASCII digits or all ASCII letters is

'/^(?:\d+|[a-zA-Z]+)$/'

See regex demo

This regex has two things your regexps do not have:

  • a grouping construct (?:....)
  • an alternation operator |.

Explanation:

  • ^ - start of string
  • (?:\d+ - one or more digits
  • | - or...
  • [a-zA-Z]+) - one or more ASCII letters
  • $ - end of string

If you need to make it Unicode-aware, use [\p{L}\p{M}] instead of [a-zA-Z] (and \p{N} instead of \d, but not necessary) and use the /u modifier:

'/^(?:\p{N}+|[\p{L}\p{M}]+)$/u'

And in case you want to really check that from the beginning to end, use

'/\A(?:\p{N}+|[\p{L}\p{M}]+)\z/u'
  ^^                        ^^

or

'/^(?:\p{N}+|[\p{L}\p{M}]+)$/Du'

The $ without /D modifier does not match the string at its "very end", it also matches if there is a newline after it as the last character.

Post Status

Asked in February 2016
Viewed 1,397 times
Voted 13
Answered 1 times

Search




Leave an answer