如何获取字符串中最长的单词?
例如。
$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/