在具有最大特定字符数的句子中查找单词

时间:2016-07-03 05:16:52

标签: php regex

我是PHP开发的新手,最后在SO的帮助下,我能够编写一个程序,用于在具有最大特定字符数的句子中查找单词。

以下是我的尝试:

<?php
// Program to find the word in a sentence with maximum specific character count
// Example: "O Romeo, Romeo, wherefore art thou Romeo?”
// Solution: wherefore 
// Explanation: Because "e" came three times
$content = file_get_contents($argv[1]); // Reading content of file
$max = 0;
$arr = explode(" ", $content); // entire array of strings with file contents
for($x =0; $x<count($arr); $x++) // looping through entire array 
{
$array[$x] = str_split($arr[$x]); // converting each of the string into array
}
for($x = 0; $x < count($arr); $x++)
{
    $count = array_count_values($array[$x]);
    $curr_max = max($count);
    if($curr_max > $max)
    {
        $max = $curr_max;
        $word = $arr[$x];
    }
}
echo $word;
?>

问题:由于我是PHP开发的新手,我不知道优化技术。无论如何我可以优化这段代码吗?另外,我可以使用正则表达式进一步优化此代码吗?请指导。

1 个答案:

答案 0 :(得分:1)

我喜欢在最少的代码行中编写这种类型的迷你挑战:D。所以这是我的解决方案:

function wordsWithMaxCharFrequency($sentence) {

    $words = preg_split('/\s+/', $sentence);

    $maxCharsFrequency = array_map (function($word) {
        return max(count_chars(strtolower($word)));
    }, $words);

    return array_map(function($index) use($words) {
        return $words[$index];
    }, array_keys($maxCharsFrequency, max($maxCharsFrequency)));
}

print_r(wordsWithMaxCharFrequency("eeee yyyy"));
//Output: Array ( [0] => eeee [1] => yyyy )

print_r(wordsWithMaxCharFrequency("xx llll x"));
//Output: Array ( [0] => llll )

<强> UPDATE1:

如果您只想获得A-Za-z字,请使用以下代码:

$matches = [];
//a word is either followed by a space or end of input
preg_match_all('/([a-z]+)(?=\s|$)/i', $sentence, $matches); 
$words = $matches[1];

只是一个可以激励你的贡献:D!

祝你好运。