0

Is there any simple way with PHP to verify that each word in a string is at least 5 characters?

I've looked into strlen and str_word_count but haven't found anything that I can use to say "if each word is N length, do this". Each word is separated by a space.

3
  • @Shlomtzion No, it's not. That's getting the length of an entire string. Not verifying the length of each individual word in a string. Commented Sep 19, 2021 at 23:25
  • 1
    Split the string, then loop the resulting array and check the length of each item in it Commented Sep 19, 2021 at 23:29
  • Note also php.net/manual/en/function.strlen.php is number of bytes rather than the number of characters. php.net/manual/en/function.mb-strlen.php would be for number of characters Commented Sep 20, 2021 at 1:35

3 Answers 3

2

Explode your string into an array, map each word to its length, call min() on the result.

function shortest_word_length($s)
{
    return min(array_map(function($word) { return strlen($word); }, explode(' ', $s)));
}
$s = 'this is a string';
echo shortest_word_length($s); // 1
Sign up to request clarification or add additional context in comments.

Comments

1

first you have to split your string to words then do that:

$str = "Hello all developers";

$arrayStr = explode(' ',$str);
// example we need to pass the first word
function checkWord($word,$max = 5) {
   return strlen($word) < 5;
}
//example we pass first word `Hello`
if (checkWord($arrayStr[0])) {
   echo "yes, it is less than 5";
} else {
   echo "sorry";
}

Comments

0

An array is formed from the string with explode(). The minimum word length is delivered directly with array_reduce() and a special user function.

$str = "Hello all friends of PHP";
$minWordLen = array_reduce(
  explode(" ",$str), 
  function($carry, $item){ 
    return ($len = strlen($item)) < $carry ? $len : $carry; 
  }, 
  PHP_INT_MAX)
;
// 2

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.