字符串中最长的单词

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.

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);

Here is another solution:

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

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

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