(PHP) randomly insert a 10 word sentence into a large text document

I have large text files of 140 or more, full of paragraphs of text, and you only need to insert a sentence into that file at arbitrary intervals if the file contains more than 200 words.

The sentence I need to randomly insert into a larger document is 10 words long.

I have full control over the server that is running my LAMP site, so I can use PHP or a linux command line app if it exists, which will do it for me.

Any ideas on how best to handle this would be greatly appreciated.

thank

Mark

+2


source to share


2 answers


You can use str_word_count()

to get the number of words in a line. From there, determine if you want to insert a row or not. As far as inserting it "at random", it can be dangerous. Do you want to suggest you paste it in a couple of random areas? If so, load the contents of the file as an array with file()

and insert the clause somewhere between $file[0]

andcount($file);



+1


source


The following code should do the trick to find and insert strings at random locations. From there, you just need to overwrite the file. This is a very crude way and doesn't account for punctuation or anything, so it will most likely need some tweaking.

$save = array();
$words = str_word_count(file_get_contents('somefile.txt'), 1);

if (count($words) <= 200)
  $save = $words;
else {
  foreach ($words as $word) {
    $save[] = $word;
    $rand = rand(0, 1000);
    if ($rand >= 100 && $rand <= 200)
      $save[] = 'some string';
  }
}

$save = implode(' ', $save);

      



This generates a random number and checks if it is included between 100 and 200, inclusive and, if so, fits into the random string. You can change the range of the random number and the number of checks to increase or decrease the number added. You can also implement a counter to do something like there must be at least x

words between each line .

Again, this doesn't account for punctuation or whatever, and just assumes all words are separated by spaces. Therefore, fine tuning may be required to improve it, but this should be a good starting point.

0


source







All Articles