【发布时间】:2011-01-04 22:35:07
【问题描述】:
如何获取字符串中最长的单词?
例如。
$string = "Where did the big Elephant go?";
返回"Elephant"
【问题讨论】:
-
到目前为止你尝试过什么?虽然有人可能会给你答案,但如果你先尝试一些东西,你会学到更多。 (而且,如果你表明你已经深思熟虑,你更有可能得到更好的答案。)
如何获取字符串中最长的单词?
例如。
$string = "Where did the big Elephant go?";
返回"Elephant"
【问题讨论】:
遍历字符串中的单词,跟踪目前最长的单词:
<?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"
?>
可以提高一点效率,但你明白了。
【讨论】:
$longestWord 而不是 $word ;)
更新:这是另一种更短的方法(这绝对是新的;)):
function reduce($v, $p) {
return strlen($v) > strlen($p) ? $v : $p;
}
echo array_reduce(str_word_count($string, 1), 'reduce'); // prints Elephant
与已经发布的类似,但使用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
【讨论】:
str_word_count()。不过,为了简洁起见,我会立即将该函数放在对 usort() 的调用中。我是 jQuery 约定的奴隶!
create_function 会解决这个问题,但事情会非常冗长。
usort( $words, function( $a, $b ) { /* code */ } ); 应该可以正常工作。这就是@lonesomeday 采用的方法。
str_word_count 放入 usort :D 我想直接传递函数,但我仍然倾向于以 5.2 风格给出答案。它更通用,知道 PHP 5.3 的人应该能够对其进行转换...
这个怎么样——按空格分割,然后按字符串长度排序,然后抓取第一个:
<?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;
编辑如果要排除标点符号,例如:“大象去哪儿了?”,可以使用preg_split:
$words = preg_split('/\b/', $string);
【讨论】:
这是另一个解决方案:
$array = explode(" ",$string);
$result = "";
foreach($array as $candidate)
{
if(strlen($candidate) > strlen($result))
$result = $candidate
}
return $result;
【讨论】:
在处理文本时这是一个非常有用的函数,因此为此目的创建一个 PHP 函数可能是个好主意:
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
在这里测试这个功能:http://ideone.com/FsnkVW
【讨论】:
一种可能的解决方案是在一个公共分隔符(例如空格)上拆分句子,然后遍历每个单词,只保留对最大单词的引用。
请注意,这将找到第一个最大的单词。
<?php
function getLargestWord($str) {
$strArr = explode(' ', $str); // Split the sentence into an word array
$lrgWrd = ''; // initial value for comparison
for ($i = 0; $i < count($strArr); $i++) {
if (strlen($strArr[$i]) > strlen($lrgWrd)) { // Word is larger
$lrgWrd = $strArr[$i]; // Update the reference
}
}
return $lrgWrd;
}
// Example:
echo getLargestWord('Where did the big Elephant go?');
?>
【讨论】: