查找每个单词出现在php中的字符串中的次数

时间:2015-09-27 18:46:42

标签: php

我有一个带有评论框textarea的HTML表单。我希望能够计算输入了多少个单词(我使用str_word_count完成了这个单词然后我希望能够告诉用户每个单词出现在字符串中的次数。我可以打印这样的值Array ( [I] => 1 [like] => 1 [comments] => 1 )但是如何输出到2列表中,它显示单词和计数?

感谢您的帮助!

表格代码:

<html>
<head>
  <title>PHP Form</title>
</head>

<body>
  <form name="newForm" method="post" action="formProcess.php">UserName:
    <input type="text" name="userName" size="15" maxlength="15">
    <br>Password:
    <input type="password" name="pass1" size="15">
    <br>Confirm Password:
    <input type="password" name="pass2" size="15">
    <br>
    <p>I agree to the terms and conditions.
      <br>
      <input type="radio" name="terms" value="yes">Yes
      <input type="radio" name="terms" value="no">No
      <p>Enter comments here:
        <br>
        <textarea name="comments" rows="6" cols="50" wrap="physical"></textarea>
        <p>
          <input type="submit" name="submitForm">
          <input type="reset" name="resetForm">
        </p>
  </form>
</body>

</html>

PHP:

<?php

$userName = $_POST[userName];
$pass1 = $_POST[pass1];
$pass2 = $_POST[pass2];
$terms = $_POST[terms];
$comments = $_POST[comments];

echo "Username: $userName<br />";
echo "Terms Agreed to? $terms<br />";
echo "Your comments: $comments<br />";

$count = str_word_count($_POST['comments']);

print_r( array_count_values(str_word_count($comments, 1)) );

echo "Total words in comment box: $count<br />";

function validatePassword($pass1,$pass2) { 
    if($pass1 === $pass2) 
        {         
          $msg = "Password confirmed!"; 
        } 
        else 
        {
          $msg = "Passwords do not match!"; 
        } 
        return $msg;
}
echo validatePassword($pass1, $pass2);
?>

2 个答案:

答案 0 :(得分:3)

您在评论中发布的代码是可以的,但它会将使用不同大小写的单词视为不同的单词(如“评论”和“评论”)。所以不要忘记使用<?php $comments = "Comments? I like comments."; $commentsArray = array_count_values(str_word_count(strtolower($comments), 1)); echo "<p>How many words were input: " . count($commentsArray) . "</p>"; ?> <table> <tr> <th>Word</th> <th>Count</th> </tr> <?php foreach($commentsArray as $word=>$count): ?> <tr> <td><?php echo $word; ?></td> <td><?php echo $count; ?></td> </tr> <?php endforeach; ?> </table>

How many words were input: 3

Word     Count
comments     2
i            1
like         1

这个脚本回应:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    Me.InfoBindingSource.RemoveCurrent()
End Sub

答案 1 :(得分:1)

显示在两列中,只是循环遍历数组。你会得到你的结果

<?php

$string = "Hello, still2blue. This is your string. This string is repeated";

$words_list = str_word_count($string, 1); // this returns the array of words 

$results = array_count_values($words_list);
foreach($results as $word => $count){
    echo sprintf("%-10s %2d", $word, $count) . PHP_EOL;
}

Example code on Ideone