replace random words in a string

﹥>﹥吖頭↗ 提交于 2019-12-10 11:51:37

问题


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.

回答1:


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:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!