计算单词出现在php数组中的次数

时间:2014-04-25 01:41:16

标签: php arrays string

我需要计算用户输入单词的次数出现在数组中。用户将文本输入到表单文本框中,该文本将转到php中的String变量,然后将其展开为一个带有每个空间索引的数组。

我需要计算每个单词出现的次数。让我们说文字是"哟哟哟哟男人男人",然后我需要计算这个词"哟"和#34; man"以及#34; man"出现。请记住,此文本可以是用户输入的任何内容,因此请使用" str_word_count"不是选项,因为它只需要硬编码的文本。

到目前为止我设置的代码:

form.php的:

<html>

    <head>

        <title>Part 1</title>

    </head>

    <body>

        <h1></h1>

        <form action="part1result.php" method = "post">

            <input type="text" name="text"/>
            <input type="submit" value="Submit" />

        </form>

    </body>

</html>

result.php:

<head>

    <title></title>

</head>

<body>

    The text you entered was:

    <?php

        $text = $_POST['text']; // get text
        $textToCount = explode(' ', $text);
        echo $text.'<br><br>';

        for($i=0; $i<count($textToCount); $i++)
        {   

        }



    ?>

</body>

1 个答案:

答案 0 :(得分:2)

使用array_count_values()

$textToCount = explode(' ', 'yo yo yo man man man');
print_r(array_count_values($textToCount));
//Array ( [yo] => 3 [man] => 3 )

foreach loop中:

$textToCount = explode(' ', 'yo yo yo man man man');
$words = array_count_values($textToCount);
foreach ($words as $word => $count) {
     printf('%s appears %u times', $word, $count);
}

请记住,标点符号可能会将其删除,因此如果允许使用标点符号,请务必在使用代码之前将其删除。

请务必将手册检查为PHP has a ton of built in functions for arraysDemo