Advertisement
dimipan80

Word Mapping

Apr 23rd, 2015
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.20 KB | None | 0 0
  1. <!--Write a PHP program WordMapper.php that takes a text from a textarea and prints each word
  2. and the number of times it occurs in the text. The search should be case-insensitive.
  3. The result should be printed as an HTML table.-->
  4.  
  5. <!DOCTYPE html>
  6. <html>
  7. <head lang="en">
  8.     <meta charset="UTF-8">
  9.     <title>Word Mapping</title>
  10.     <style type="text/css">
  11.         table, td {
  12.             background-color: #eee;
  13.             border: 1px solid #000;
  14.         }
  15.     </style>
  16. </head>
  17. <body>
  18. <form method="post">
  19.     <textarea name="text" cols="60" rows="5" placeholder="Enter your text..."></textarea>
  20.  
  21.     <p><input type="submit" value="Count words"/></p>
  22. </form>
  23. <table>
  24.     <tbody>
  25.     <?php
  26.     if (!isset($_POST) || !isset($_POST['text']) || trim($_POST['text']) === '') {
  27.         die("The Input Form can't been Empty!!!");
  28.     }
  29.  
  30.     $text = strtolower(trim($_POST['text']));
  31.     $words = str_word_count($text, 1);
  32.     $resultMap = array();
  33.     foreach ($words as $word) {
  34.         if (!array_key_exists($word, $resultMap)) {
  35.             $resultMap[$word] = 1;
  36.         } else {
  37.             $resultMap[$word] += 1;
  38.         }
  39.     }
  40.  
  41.     foreach ($resultMap as $key => $number):?>
  42.         <tr>
  43.             <td><?= $key ?></td>
  44.             <td><?= $number ?></td>
  45.         </tr>
  46.     <?php endforeach; ?>
  47.     </tbody>
  48. </table>
  49. </body>
  50. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement