Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex to match only 5 letter words

Tags:

regex

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.

like image 378
iwek Avatar asked Jan 18 '23 11:01

iwek


2 Answers

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');
like image 99
Benjie Avatar answered Jan 24 '23 22:01

Benjie


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

/\b\w{1,5}\b/
like image 36
Ludovic Kuty Avatar answered Jan 24 '23 22:01

Ludovic Kuty