Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Longest word in a string

Tags:

string

php

How can I get the longest word in a string?

Eg.

$string = "Where did the big Elephant go?";

To return "Elephant"

like image 366
Frank Nwoko Avatar asked Nov 28 '22 12:11

Frank Nwoko


2 Answers

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.

like image 164
Lightness Races in Orbit Avatar answered Dec 09 '22 14:12

Lightness Races in Orbit


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
like image 38
Felix Kling Avatar answered Dec 09 '22 14:12

Felix Kling