chubbyk
chubbyk

Reputation: 6302

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 ?

Upvotes: 4

Views: 4405

Answers (2)

lonesomeday
lonesomeday

Reputation: 238065

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.

Upvotes: 7

H&#229;vard
H&#229;vard

Reputation: 10080

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

Upvotes: 10

Related Questions