How to validate that a string only contain lowercase letters?

后端 未结 3 832
日久生厌
日久生厌 2020-12-04 01:40

I\'m trying to verify that my string matches a pattern. That is, the full string can be written as that pattern. However preg_match returns true, i

3条回答
  •  难免孤独
    2020-12-04 02:20

    Note that the $ anchor also matches before the line break char sequence that is at the very end of the string (yes, even if m MULTILINE flag is not specified). See these tests, all returning a match:

    if (preg_match("#^[a-z]*$#", "ok")) echo "OK!\n"; // => is OK!
    if (preg_match("#^[a-z]*$#", "ok\n")) echo "OK!\n"; // => is OK!
    if (preg_match("#(*ANY)^[a-z]*$#", "ok\r\n")) echo "OK!"; // => is also OK!
    

    You may "fix" this $ behavior by using the D modifier. The PCRE-compliant PCRE_DOLLAR_ENDONLY modifier makes the $ anchor match at the very end of the string (excluding the position before the final newline in the string).

    /^\d+$/D
    

    is equal to

    /^\d+\z/
    

    and matches a whole string that consists of 1 or more digits and will not match "123\n", but will match "123".

    Alternatively, to anchor the string match at the very start and end of the string you might also consider using \A and \z anchors.

    preg_match('~\A[a-z]*\z~', "333k");
                 ^^      ^^
    

    The \A and \z are unambiguous start and end of string anchors in PHP regex (as their behavior does not depend on any regex modifiers, even if you specify the m MULTILINE modifier, they will keep on asserting string start/end positions). See more on PHP regex anchors in PHP documentation.

    Beware of \Z though: \Z will match the whole string before the last single linebreak, whereas \z will only match at the very end of the string, that is, after all the characters there are in the string (see Whats the difference between \z and \Z in a regular expression and when and how do I use it?)

提交回复
热议问题