Guys,

I'm trying to use a regex in preg_match to exclude strings that don't begin with a-z, A-Z or ,
have any remaining chars that are a-z, A-Z, 0-9 or
and that DO NOT include white space.

The expression /[a-zA-Z][a-zA-Z0-9]*/ produces the following results when passed the strings:

abc (passes - ok)
ab c (passes - should fail)
abc= (passes - should fail)

What am I missing?

    Your pattern needs to look at the entire string (i.e., start-to-end).

    /^[a-zA-Z_][a-zA-Z0-9_]*$/

    Also, note that you can simplify this pattern by making it case-insensitive:

    /^[a-z_][a-z0-9_]*$/i

    Or by using extended character classes:

    /^[a-z_]\w*$/i

      Use a $ to match the end of the string probaly:

      /^[a-zA-Z_][a-zA-Z0-9_]*$/

      Edit: What traq said.

        hey, related question: does anyone know how well PHP supports character "property" classes? e.g., [font=monospace]\p{L}[/font] ("match character property: is a Letter")?

        It seems to work in 5.4+. Anyone have info on earlier versions? or if support might vary depending on other factors?

        @: this is "related" because it would allow you to use [font=monospace]/\p{L}\w*$/[/font] for your pattern. (Maybe you could see if that works on your installation.)

          hey, sweet. I was looking in the wrong section. Thanks!

            Write a Reply...