字符串中最长的单词

Fra*_*oko 4 php string

如何获得字符串中最长的单词?

例如.

$string = "Where did the big Elephant go?";
Run Code Online (Sandbox Code Playgroud)

回来 "Elephant"

Lig*_*ica 15

循环遍历字符串的单词,跟踪到目前为止最长的单词:

<?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"
?>
Run Code Online (Sandbox Code Playgroud)

可以提高效率,但你明白了.

  • @JMCCreative:我很棒. (4认同)
  • 你在15秒内写下了什么?! (3认同)
  • @Tomalak你的精彩应该回应`$ longestWord`而不是'$ word`;) (2认同)
  • @Tomalak:为什么不承认这个解决方案(虽然快速发布)还没有完成,并修复它. (2认同)
  • @mvds:好的,我放弃了.这是一个最长的令牌发现示例. (2认同)

Fel*_*ing 9

更新:这是另一个更短的方式(这一个肯定是新的;)):

function reduce($v, $p) {
    return strlen($v) > strlen($p) ? $v : $p;
}

echo array_reduce(str_word_count($string, 1), 'reduce'); // prints Elephant
Run Code Online (Sandbox Code Playgroud)

与已发布的相似,但str_word_count用于提取单词(通过在空格处分割,标点符号也将计算在内):

$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
Run Code Online (Sandbox Code Playgroud)