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