Reputation: 321
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.
Upvotes: 0
Views: 618
Reputation: 7693
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
Upvotes: 0
Reputation: 23840
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
Upvotes: 2
Reputation: 1259
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";
}
Upvotes: 1