问题
I want to create a function that replaces random words in a string. Here is what I thought of.
- Given a string I would give a random index position within that string.
- From that index I will replace the nearest word with a word that I want
- 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:
- The apple brown fox jumps cat the lazy dog.
- The quick brown wolf tree over the lazy dog.
- The quick tree fox tree over the lazy apple.
回答1:
The clearest code would be had by
- Splitting the string into an array words (e.g. with
explode
orpreg_split
for more heavy-duty logic) - Replacing randomly selected entries in the array as you see fit
- Joining the words back into a string with (e.g.
implode
)
回答2:
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
?>
来源:https://stackoverflow.com/questions/10447943/replace-random-words-in-a-string