php - How to match trailing linefeed with regexp? -
i'm trying validate string trailing whitespace/linefeed (php_eol, \n, \r, \t , " ") not allowed. here's code:
$pattern = '/^[a-za-z0-9 ]+?[^\s]$/'; $value = 'foo' . php_eol; $status = preg_match($pattern, $value); with trailing php_eol , "\n" expression matches, "\t", "\r" , " " doesn't.
what proper expression disallow whitespace/linefeed @ end of string, including php_eol , "\n"?
the problem $ is, matches @ end of string or before newline character last character in string (by default), therefore can not match \n @ end of string using $ anchor.
to avoid can use \z (see escape sequences on php.net), match @ end of string (also independently of multiline modifier).
so solution be
$pattern = '/^[a-za-z0-9 ]+?(?<!\s)\z/'; (?<!\s) negative lookbehind assertion, true if there no whitespace character before \z
Comments
Post a Comment