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.
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');
Use the regex below to match words from 1 to 5 characters. \b
is a word boundary
/\b\w{1,5}\b/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With