gpt4 book ai didi

php - 字符串中最长的单词

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:51:47 25 4
gpt4 key购买 nike

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

例如。

$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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com