Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression pattern for any string with specific length

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 ?

like image 646
chubbyk Avatar asked Dec 04 '22 08:12

chubbyk


2 Answers

/^.{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.

like image 199
Håvard Avatar answered Dec 28 '22 07:12

Håvard


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.

like image 43
lonesomeday Avatar answered Dec 28 '22 08:12

lonesomeday