2

Using PHP's preg_match() function, how would I go about matching words that are between 2 and 5 characters? In this case the letters are guaranteed to be uppercase A-Z and there is only one word in each $word variable.

It must reject a word of 6 characters:

preg_match("/[A-Z]{2,5}/", $word); 

...does not appear to work, presumably because a 6 character $word will match based on the first 2-5 characters.

This is a simplified version of my actual problem which cannot be solved with a strlen() test.

4

1 回答 1

3

Your post was not clear if you wanted the string to be exactly A-Z between 2 and 5 characters. This will match all words in a string between 2-5 characters:

preg_match('/\b[A-Z]{2,5}\b/', $string, $matches);
var_dump($matches);

If you just the string to be exactly between 2 and 5 characters and only consisting of A-Z:

preg_match('/^[A-Z]{2,5}$/', $word);
于 2013-01-18T15:00:07.800 回答