0
votes

I want to create a function that replaces random words in a string. Here is what I thought of.

  1. Given a string I would give a random index position within that string.
  2. From that index I will replace the nearest word with a word that I want
  3. Along with that I would store the word I just replace into some storage variable/database/file

Ex.

Random word seed: tree, cat, wolf, apple

String: The quick brown fox jumps over the lazy dog.

Possible Results:

  1. The apple brown fox jumps cat the lazy dog.
  2. The quick brown wolf tree over the lazy dog.
  3. The quick tree fox tree over the lazy apple.
2
get length of string -> get random integer within that range -> get character at that index, if whitespace increment index till you find a word. -- best would be to use regular expressions i guessAntwan van Houdt

2 Answers

1
votes

The clearest code would be had by

  1. Splitting the string into an array words (e.g. with explode or preg_split for more heavy-duty logic)
  2. Replacing randomly selected entries in the array as you see fit
  3. Joining the words back into a string with (e.g. implode)
2
votes

Simply explode the string on spaces, and use a rand() to replace. Like:

<?php
$string = "The quick brown fox jumps over the lazy dog.";
$aWords = explode($string, " ");
foreach ($aWords as $word)
{
    if(rand(1,2) == 1)
    {
        //replace the word
    }
}
// implode the string
?>