php - 字符串中最长的单词

标签 php string

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

例如。

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

返回“大象”

最佳答案

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

<?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"
?>

可以提高一点效率,但您明白了。

关于php - 字符串中最长的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4599174/

相关文章:

php - Symfony 3 - 如何防止sql表出现重复行

C语言: Search text file for a "var" and store the next string as the value

string - 如何将 Erlang 记录从字符串表示形式转换回记录?

php - 将 "clean"信息存储在 SQL 数据库中的最佳方法是什么?

javascript - jQuery $.post 不工作,但 $.ajax post 工作

c# - 在 C# 中解密用 PHP openssl_encrypt 加密的字符串

c# - 如何修剪字符串中的前导逗号

PHP比较二维数组

java - 字符串函数 - ReplaceAll 不适用于 "."

string - 如何检测字符串中的字符是大写还是小写?