iwek
iwek

Reputation: 1608

regex to match only 5 letter words

I have an array and want to retrieve only 5 letter words, nothing longer, I have tried to use

$new = preg_grep("/.{5}/", $array);

but that resulted in any word that is at least 5 letters long. I want any word that is at most 5 letters long.

Upvotes: 5

Views: 49150

Answers (5)

Ludovic Kuty
Ludovic Kuty

Reputation: 4954

Use the regex below to match words from 1 to 5 characters. \b is a word boundary

/\b\w{1,5}\b/

Upvotes: 4

Benjie
Benjie

Reputation: 7946

You need to use the start (^) and end ($) modifiers, so

$new = preg_grep("/^.{5}$/", $array);

However, more efficient might be to just do a strlen based filter:

function len5($v){
   return strlen($v) == 5;
}
$new = array_filter($array, 'len5');

Upvotes: 9

Kashyap
Kashyap

Reputation: 17524

That will match in middle of a word as well. You need the word boundary switch I think it's \w

See this: http://www.regular-expressions.info/wordboundaries.html

Upvotes: 0

Amber
Amber

Reputation: 527213

Add start (^) and end ($) markers:

$new = preg_grep("/^.{5}$/", $array);

Upvotes: 0

Vivin Paliath
Vivin Paliath

Reputation: 95578

Your question is not clear. Do you want words that are only 5 letters long, or at most 5 letters long. Those are two separate things.

For the former:

$new = preg_grep("/^.{5}$/", $array);

For the latter:

$new = preg_grep("/^.{1,5}$/", $array);

The ^ and $ anchors mark the beginning and end of the line respectively. If you didn't have markers, you would match a word like abcdef because abcde will match against your regular expression. You want to specify that you want to match against the entire string and not just the part of the string.

Upvotes: 0

Related Questions