Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Replacing spaces in sentences with random words



6:00 am on Nov 16, 2010 (gmt 0)

10+ Year Member

I have an array of random words (apple, orange, banana) that I wish to replace spaces in a sentence, randomly.

So if I have:

The quick brown fox jumped over the lazy dog.

It would become:

The apple quick banana brown apple fox orange jumped banana over orange the apple lazy banana dog.

Here is the code, which doesn't quite work. It inserts the same word over and over for each space instead of picking a random word from the array for each space.

$string = $desc_jj;
$replaceme = ' ';
$replacewith = ' ' . $desc_kw_array_kw[array_rand($desc_kw_array_kw)] . ' ';
$nthtimes = 2;
$desc_jj = preg_replace("/((.*?)(".$replaceme.")){".$nthtimes."}/e", '(preg_replace("/".$replaceme."$/", "", "\0")).$replacewith', $string);

Any ideas anyone?



8:57 am on Nov 16, 2010 (gmt 0)

5+ Year Member

because the array_rand() only run once.
So you migh need to "re-pick" again for each time.
you might need to use a loop, or create/call a RandomPickFruit() function everytime u gonna replace the new word from array.


6:25 am on Nov 18, 2010 (gmt 0)

10+ Year Member

I'll try that, thanks!


9:49 pm on Nov 19, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member

It sounds like you might need more than just a loop. If I understand you correctly, you want to replace some of the spaces with a randomly chosen word. Am I correct? If so, you'll need to randomly decide whether or not to replace each space, and if that space is to be replaced, choose a random word.

In any case, this is a perfect situation to use preg_replace_callback() [php.net].

That function allows you to specify a function instead of a replacement string, so you'd have something like this:

function random_replace() {
$replacements = array('lorem', 'ipsum', 'dolor', 'sit', 'amet');
return rand(0,1) ? ' '. $replacements[rand(0, 4)]. ' ' : ' ';

$string = 'The quick brown fox jumped over the lazy dog.';
$pattern = '/\s/';
$results = preg_replace_callback($pattern, 'random_replace', $string);

Tested and working, though it doesn't consider the possibility of doubled spaces (if it runs into two spaces, it could return two words in a row).

-- b

Featured Threads

Hot Threads This Week

Hot Threads This Month