How can I get the longest word in a string?
Eg.
$string = "Where did the big Elephant go?";
To return "Elephant"
Loop through the words of the string, keeping track of the longest word so far:
<?php
$string = "Where did the big Elephant go?";
$words = explode(' ', $string);
$longestWordLength = 0;
$longestWord = '';
foreach ($words as $word) {
if (strlen($word) > $longestWordLength) {
$longestWordLength = strlen($word);
$longestWord = $word;
}
}
echo $longestWord;
// Outputs: "Elephant"
?>
Can be made a little more efficient, but you get the idea.
Update: Here is another even shorter way (and this one is definitely new ;)):
function reduce($v, $p) {
return strlen($v) > strlen($p) ? $v : $p;
}
echo array_reduce(str_word_count($string, 1), 'reduce'); // prints Elephant
Similar as already posted but using str_word_count
to extract the words (by just splitting at spaces, punctuation marks will be counted too):
$string = "Where did the big Elephant go?";
$words = str_word_count($string, 1);
function cmp($a, $b) {
return strlen($b) - strlen($a);
}
usort($words, 'cmp');
print_r(array_shift($words)); // prints Elephant
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