Proofing Class-Name with preg_match

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Mat Son
    New Member
    • Jul 2011
    • 7

    Proofing Class-Name with preg_match

    Hello guys,

    I just started with using Regular Expressions and I already found some good regex´ on the net, but I´d prefer to have my own version working.
    I want to check that my AutoLoader only allows for class or interface names that consist of a-z, A-Z and 0-9 letters and that it begins with an uppercase letter.

    Code:
    if(preg_match("/^([A-Z]+[a-z0-9]*)([A-Z]*[a-z0-9]*)*/", $class, $name)) {
    			echo $name[0];
    		} else {
    			echo "invalid class name<br>";
    		}
    This works so far fine, but when I now put in something like: "ThisIsAClass_T est", the result is "ThisIsACla ss" and the preg_match returns true.
    I do, however, understand that the regex is matched, because there IS an Uppercase letter first, followed by none ore more lower case letters, followed by none ore more upper and lowercase letters.
    But how do I tell him that I don't allow anything other then A-Z, a-z and 0-9?

    Thanks in advance for your help.
  • Anas Mosaad
    New Member
    • Jan 2013
    • 185

    #2
    I think you need to add something that tells the matcher search within the word boundaries (i.e. \b option).

    Also, I believe your expression can be a bit simplified to
    Code:
    [A-Z][a-zA-Z0-9]*

    Comment

    • Rabbit
      Recognized Expert MVP
      • Jan 2007
      • 12517

      #3
      You anchored the beginning of the term with the ^ character. Just anchor the end with the $ character.

      Comment

      Working...