help writing an expression

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
gammaman
Forum Commoner
Posts: 45
Joined: Tue Feb 12, 2008 9:22 am

help writing an expression

Post by gammaman »

I need an expression that does the following

A length of six characters with the first character being a letter. It must contain at least on upper case letter, a number and a symbol (% or # or ~).
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: help writing an expression

Post by prometheuzz »

gammaman wrote:I need an expression that does the following

A length of six characters with the first character being a letter. It must contain at least on upper case letter, a number and a symbol (% or # or ~).

Trying to do it all in one match would be madness, break it up in several matches:

Code: Select all

function is_valid($text) {
    return preg_match('/^[a-zA-Z][a-zA-Z\d%#~]{5}$/', $text) && // starts with a letter, followed by 5  
                                                                // characters in the set [a-zA-Z\d%#~]
           preg_match('/\d/', $text) &&                         // contains a number
           preg_match('/[a-z]/', $text) &&                      // contains a lower case letter
           preg_match('/[A-Z]/', $text) &&                      // contains an upper case letter
           preg_match('/[%#~]/', $text);                        // contains one of %, # or ~
}
Post Reply