Advertisement
Guest User

Untitled

a guest
Mar 16th, 2011
341
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.70 KB | None | 0 0
  1. <?php
  2.  
  3. $fname = "textfile.txt";
  4. $data = file_get_contents($fname);          // Load file from disk as string.
  5.  
  6.  
  7. if ($_POST['Submit'])                       // Only add the data if Submit is set.
  8. {
  9.     $text = $_POST['update'];
  10.     $text = strip_tags($text);              // Remove any HTML from input.
  11.     $text = str_replace(",", "", $text);    // Remove commas from input.
  12.     $text = explode(" ", $text);            // Split text at every space.
  13.  
  14.     $to_add = array();                      // List of cleansed words to add to file.
  15.  
  16.     // Clean the words and check if they're in the file aready.
  17.     foreach ($text as $word)                // Loop through each word...
  18.     {
  19.         $word = trim($word);                // Trim any remaining whitespace (tabs, \r, \n, etc)
  20.         if (empty($word)) { continue; }     // Skip if $word is empty after removing whitespace.
  21.    
  22.         if (stripos($data, $word) !== FALSE)    // Using stripos, not stristr because we only need to know if it's there.
  23.         {
  24.             echo "'$word' is already in the file.<br />";
  25.            
  26.         } else {    // Word isn't in the file, add to list of words to write
  27.             $to_add[] = $word;
  28.         }
  29.     }
  30.    
  31.     // Time to add the words to the file
  32.     $out = fopen($fname, "a");              // Open file for writing *only*, no need for "+"
  33.    
  34.     foreach ($to_add as $word)
  35.     {
  36.         fwrite($out, $word ."\n");
  37.         echo "Added '$word' to the file.<br />";
  38.     }
  39.     fclose($out);                           // Close the file handle, we're done writing
  40.  
  41. }
  42.  
  43. // Regardless of if new data was added, display the file contents in a text box
  44. echo "<textarea>". $data ."</textarea>";
  45.  
  46. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement