#1
  1. Put a potato on it!
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2008
    Location
    Maryland
    Posts
    304
    Rep Power
    971

    Why does the order matter?


    I'm not good with regex, much more than email validation loses me. But I'm working on an older code repo that has some filtering going on for its form validation functions.

    This is how the function validates a person's first or last name:

    PHP Code:
    filter_var('3 32pm'FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/[a-zA-Z][a-zA-Z0-9-_\.]{2,32}/"))); 
    And in testing our form out, my coworker put in "3 32 pm" in the last name field. The validation failed so I took the above snippet and tested it with the following values with the respective values returned by var_dump():

    3 32 pm - false
    pm3 32 - pm3 32
    3 pm32 - 3 pm32
    3pm pm32 - 3pm pm32
    3 pm 32 - false

    I rearranged the regex like so, with the number range first:

    PHP Code:
    filter_var('3 pm 32'FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/[0-9a-zA-Z][a-zA-Z-_\.]{2,32}/"))); 
    And tested the above values that produced a false result before; this time they returned the filtered string, rather than false.

    What I don't understand is why the order mattered here, shouldn't the PHP function evaluate the entire string before returning a value? If my input contained '$' or '@' I'd expect it to be removed, but this thing with the numbers seems odd. I can't think of why someone would put the time in for their name and I can fix this bug, but the issue is still really weird.
    "Those who can make you believe absurdities can make you commit atrocities."
  2. #2
  3. Transforming Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,141
    Rep Power
    9398
    It's not order. You changed the regex. You changed the definition of what's valid and what isn't. Before it was failing names because they started with a number. Now that you've told it that a leading number is okay it will not fail them.
  4. #3
  5. Put a potato on it!
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2008
    Location
    Maryland
    Posts
    304
    Rep Power
    971
    That actually answers the other question I couldn't figure out. I had (inaccurately, I realize now) thought that a regex expression could be ordered in any way and it would work the same way. But when I think of symbols such as "*", "^" and "?" I realize that's incorrect.

    Thanks, Requinix, some more fundamentals just clicked for me.
    "Those who can make you believe absurdities can make you commit atrocities."

IMN logo majestic logo threadwatch logo seochat tools logo