I'm trying to validate string so that trailing whitespace/linefeed (PHP_EOL, \n, \r, \t and " ") is not allowed. Here's the code:
$pattern = '/^[a-zA-Z0-9 ]+?[^\s]$/';
$value = 'foo' . PHP_EOL;
$status = preg_match($pattern, $value);
With trailing PHP_EOL and "\n" expression matches, with "\t", "\r" and " " it doesn't.
What is the proper expression to disallow all whitespace/linefeed at the end of the string, including PHP_EOL and "\n"?
The problem with $
is, that it matches at the end of the string or immediately before a newline character that is the last character in the string (by default), therefore you can not match a \n
at the end of the string using the $
anchor.
To avoid that you can use \z
(see escape sequences on php.net), that will always match at the end of the string (also independently of the multiline
modifier).
So a solution would be
$pattern = '/^[a-zA-Z0-9 ]+?(?<!\s)\z/';
(?<!\s)
is a negative lookbehind assertion, that is true if there is no whitespace character before \z
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With