homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

Replacing spaces in sentences with random words

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

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)

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)

I'll try that, thanks!


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

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

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved