Dave
Dave

Reputation: 29121

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)

Upvotes: 7

Views: 11189

Answers (4)

Justin Morgan
Justin Morgan

Reputation: 30695

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.

Upvotes: 2

Tomalak
Tomalak

Reputation: 338128

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 (a.k.a DOTALL) regex flag /…/s

Upvotes: 7

JAB
JAB

Reputation: 21079

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

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190897

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';

Upvotes: 6

Related Questions