I want to build pattern for preg_match that will match any string with length 1 - 40 chars. I found this:
^[^<\x09]{1,40}\Z
But with that one I recieve this error message:
function.preg-match]: Unknown modifier '<' in ....
Any suggestion ?
/^.{1,40}$/
should match any string that's 1 to 40 characters long.
What it does is that it takes the .
, which matches everything, and repeats it 1 to 40 times ({1,40}
). The ^
and $
are anchors at the beginning and end of the string.
If you don't care what the characters are, you don't need regex. Use strlen
to test the length of a string:
if ((strlen($yourString) <= 40) && (strlen($yourString) >= 1)) {
}
This will be far faster than booting up the PCRE engine.
Addendum: if your string may contain multi-byte characters (e.g. é
), you should use mb_strlen
, which takes these characters into consideration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With