Reputation: 29121
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
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
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:
.
to [\s\S]
(whitespace/newlines are part of \s
, all the rest is part of \S
)/…/s
Upvotes: 7
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