Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match trailing linefeed with regexp?

Tags:

regex

php

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"?

like image 823
Eero Niemi Avatar asked Nov 02 '22 22:11

Eero Niemi


1 Answers

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

like image 75
stema Avatar answered Nov 09 '22 11:11

stema