Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $fname = "textfile.txt";
- $data = file_get_contents($fname); // Load file from disk as string.
- if ($_POST['Submit']) // Only add the data if Submit is set.
- {
- $text = $_POST['update'];
- $text = strip_tags($text); // Remove any HTML from input.
- $text = str_replace(",", "", $text); // Remove commas from input.
- $text = explode(" ", $text); // Split text at every space.
- $to_add = array(); // List of cleansed words to add to file.
- // Clean the words and check if they're in the file aready.
- foreach ($text as $word) // Loop through each word...
- {
- $word = trim($word); // Trim any remaining whitespace (tabs, \r, \n, etc)
- if (empty($word)) { continue; } // Skip if $word is empty after removing whitespace.
- if (stripos($data, $word) !== FALSE) // Using stripos, not stristr because we only need to know if it's there.
- {
- echo "'$word' is already in the file.<br />";
- } else { // Word isn't in the file, add to list of words to write
- $to_add[] = $word;
- }
- }
- // Time to add the words to the file
- $out = fopen($fname, "a"); // Open file for writing *only*, no need for "+"
- foreach ($to_add as $word)
- {
- fwrite($out, $word ."\n");
- echo "Added '$word' to the file.<br />";
- }
- fclose($out); // Close the file handle, we're done writing
- }
- // Regardless of if new data was added, display the file contents in a text box
- echo "<textarea>". $data ."</textarea>";
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement