4

How can I get the longest word in a string?

Eg.

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

To return "Elephant"

zx8754
  • 52,746
  • 12
  • 114
  • 209
Frank Nwoko
  • 3,816
  • 5
  • 24
  • 33
  • 8
    What have you tried so far? While someone may give you the answer, you'll learn a lot more if you try some stuff out first. (And, you're more likely to get a lot better answer if you show you've put some thought into it.) – JasCav Jan 04 '11 at 22:36

7 Answers7

17

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
10

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
Gueno
  • 197
  • 10
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • +1 for using `str_word_count()`. I would have placed the function immediately inside the call to `usort()` for brevity though. I'm a slave to jQuery conventions! – Sampson Jan 04 '11 at 22:51
  • I don't like the need to create a function (and pollute the symbol table) though! `create_function` would fix that but then things are very verbose. – Lightness Races in Orbit Jan 04 '11 at 22:54
  • @Tomalak Geret'kal: I don't like it either, but sometimes it is unavoidable (not saying that this is the case here). – Felix Kling Jan 04 '11 at 22:56
  • @Felix I'm not sure what you mean by not having a reference to your array. I was suggesting `usort( $words, function( $a, $b ) { /* code */ } );` Should work with no problems. This was the method that @lonesomeday went with. – Sampson Jan 04 '11 at 23:02
  • @Jonathan Sampson: Ah I thought you mean to put the function `str_word_count` into `usort` :D I'd like to pass functions directly but I still tend to give answers in 5.2 style. It's more general and those aware of PHP 5.3 should be able to transform it... – Felix Kling Jan 04 '11 at 23:05
2

How about this -- split on spaces, then sort by the string length, and grab the first:

<?php

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

$words = explode(' ', $string);

usort($words, function($a, $b) {
    return strlen($b) - strlen($a);
});

$longest = $words[0];

echo $longest;

Edit If you want to exclude punctuation, for example: "Where went the big Elephant?", you could use preg_split:

$words = preg_split('/\b/', $string);
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
0

This is a quite useful function when dealing with text so it might be a good idea to create a PHP function for that purpose:

function longestWord($txt) {
    $words = preg_split('#[^a-z0-9áéíóúñç]#i', $txt, -1, PREG_SPLIT_NO_EMPTY);
    usort($words, function($a, $b) { return strlen($b) - strlen($a); });
    return $words[0];
}
echo longestWord("Where did the big Elephant go?");
// prints Elephant

Test this function here: http://ideone.com/FsnkVW

0

Here is another solution:

$array = explode(" ",$string);
$result = "";
foreach($array as $candidate)
{
if(strlen($candidate) > strlen($result))
$result = $candidate
}
return $result;
Brent
  • 1
  • 1
0

A possible solution would be to split the sentence on a common separator, such as spaces, and then iterate over each word, and only keep a reference to the largest one.

Do note that this will find the first largest word.

<?php
function getLargestWord($str) {
  $strArr = explode(' ', $str); // Split the sentence into an word array
  $lrgWrd = ''; // initial value for comparison
  for ($i = 0; $i < count($strArr); $i++) {
    if (strlen($strArr[$i]) > strlen($lrgWrd)) { // Word is larger
      $lrgWrd = $strArr[$i]; // Update the reference
    }
  }
  return $lrgWrd;
}
// Example:
echo getLargestWord('Where did the big Elephant go?');
?>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Biswajit Biswas
  • 859
  • 9
  • 20
  • While the code provided answers the question, you could assume that people reading the question would not understand it, please, provide comments explaining what you are doing, since this simpler question. – Bonatti Jan 03 '20 at 18:11
0
$string ='Where did the big Elephant';
function longestWord($str) {
$str.=" ";
$ex ="";
$max ="";
for($i = 0; $i < strlen($str); $i++)
{
    if($str[$i]==" ")
    {
        if(strlen($ex) > strlen($max))
            $max = $ex; 
            $ex ="";
    }else
    {
        $ex.=$str[$i];             
    }
}
return $max;
}
echo longestWord($string);
makisa
  • 1
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Amit May 03 '22 at 12:12