简体   繁体   中英

Regular expression for length only - any characters

I'm trying to regex the contents of a textarea to be between 4 and 138 characters.

My regular expression is this: '/^.{4,138}$/'

But - I want the user to be able to include return characters, which I believe the "." keeps them from doing. Thoughts on what I need to change?

EDIT:

Obviously there are other ways to get the length of text - strlen ...etc, but I'm looking for regex specifically due to the nature of the check (ie a plugin that requires regex)

I want the user to be able to include return characters, which I believe the "." keeps them from doing. Thoughts on what I need to change?

Either:

  • change the . to [\s\S] (whitespace/newlines are part of \s , all the rest is part of \S )
  • use the SINGLE_LINE (aka DOTALL) regex flag /…/s

Why don't you just check the string length using strlen ? It would be much more efficient than doing a regex. Plus, you can give meaningful error messages.

$length = strlen($input);

if ($length > 138)
   print 'string too long';
else if ($length < 4)
   print 'string too short';

Either

/^.{4,138}$/s

or

/^[\s\S]{4,138}$/ 

will match newlines.

The s flag tells the engine to treat the whole thing as a single line, so . will match \n in addition to what it usually matches. Note that this also causes ^ and $ to match at the beginning and end of the entire string (rather than just the beginning/end of each line ) unless you also use the m flag.

Here's some more info on regex flags.

Try '/^.{%d,%d}$/s' to have . match newlines as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM