Need help with preg_match

Hi there…

I really need help with my ugly regex code because it still can’t diferrentiate string and string contain only numbers ok here the scenario;

All the string must meet this 3 conditions

1.String contain only alpha,space and dot
2.String contain only alphanumeric,space and dot
3.String contain only numbers

so here’s my attempt code so far




$testStringArray = array("abc. bc. def83","abc. bc.","123","567","fdg. qwe.","dfg. rtu. hu8");

//so i start filter testing here

$total = count($testStringArray);

for($i=0;$i<$total;$i++){
   if(preg_match('/[a-zA-Z.\\...\\\\s.]+$/',$testStringArray[$i])){
            echo $i." : ".$testStringArray[$i]." contain only alpha,dot,space";
  }else if(preg_match('/^[a-zA-Z0-9.\\...\\\\s.]+$/i/',$testStringArray[$i])){
           echo $i." : ".$testStringArray[$i]." contain only alpha,dot,numbers,space";
  }else if(preg_match('/^[0-9]/',$testStringArray[$i])){
      echo $i." : ".$testStringArray[$i]." contain only numbers";
  }

}


Current output:

contain only alpha,dot,numbers,space
contain only alpha,dot,space
contain only alpha,dot,numbers,space–>it seems the regex not wokr here
contain only alpha,dot,numbers,space–>it seems the regex not wokr here
contain only alpha,dot,space
contain only alpha,dot,numbers,space

suppose to :

contain only alpha,dot,numbers,space
contain only alpha,dot,space
contain only numbers—>shoud be numbers only
contain only numbers—>shoud be numbers only
contain only alpha,dot,space
contain only alpha,dot,numbers,space

So i really need help with it…thanks in advance guys…

You need to check /[0-9]/ before you check /[1]+$/i/

Because everything that matches /[0-9]/ will also match /[2]+$/i/ and therefore get matched in the second if()
The other way around is not true, so you should check if a string consists of only digits before you check if it consists of digits among others.

BTW. No offence, but your regexes are weird.
Why dont you use:


/^[a-zA-Z\\.\\s]+$/

instead of

/[a-zA-Z.\\...\\\\s.]+$/


/^[a-zA-Z\\d\\.\\s/]+$/

instead of

^[a-zA-Z0-9.\\...\\\\s.]+$/i/

Note that \d = [0-9], and /i (making the regex case insensitive) is not needed since you already check for uppercase and lowercase chars


/^[0-9]$/

instead of

/^[0-9]$/

You forgot the $ at the end :slight_smile:


  1. a-zA-Z0-9.\…\\s. ↩︎

  2. a-zA-Z0-9.\…\\s. ↩︎