Regular expression for length only - any characters
I'm try开发者_StackOverflow中文版ing 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 (a.k.a 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.
精彩评论