Regular expression pattern for any string with a specific length

I want to create a template for preg_match that matches any string 1 to 40 characters long. I found this:

^[^<\x09]{1,40}\Z 

But with this, I get this error message:

 function.preg-match]: Unknown modifier '<' in .... 

Any suggestion?

+4
source share
2 answers

/^.{1,40}$/ must match any line between 1 and 40 characters long.

What he does is what he accepts . , which matches all, and repeats it 1 to 40 times ( {1,40} ). ^ and $ are anchors at the beginning and end of the line.

+10
source

If you do not care what characters, you do not need a regular expression. Use strlen to check the length of a string:

 if ((strlen($yourString) <= 40) && (strlen($yourString) >= 1)) { } 

This will be much faster than loading the PCRE processor.


Addendum: if your string can contain multibyte characters (e.g. é ), you should use mb_strlen , which takes these characters into account.

+7
source

All Articles