如何获得字符串中最长的单词?
例如.
$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)
可以提高效率,但你明白了.
更新:这是另一个更短的方式(这一个肯定是新的;)):
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)
| 归档时间: |
|
| 查看次数: |
7731 次 |
| 最近记录: |