user892970
user892970

Reputation: 73

PHP Replace a word with a random word from a list?

Using PHP, I'm looking to take a piece of text and search through it and replace certain words with another word from the list.

e.g.

Search through the text to find any word in this list: pretty,beautiful,gorgeous,lovely,attractive,appealing

and then replace this word with another from the same list (but not selecting the same word).

Hope this makes sense!

thanks in advance.

Upvotes: 1

Views: 761

Answers (1)

knittl
knittl

Reputation: 265211

you could use preg_replace_callback:

$random_string = '…';
$needle = array('pretty', 'beautiful', 'gorgeous', 'lovely', 'attractive', 'appealing');
$new_string = preg_replace_callback(
  array_map(
    function($v) { return '/'.preg_quote($v).'/'; }, // assuming $needle does not contain '/' 
    $needle),
  function($matches) use($needle) {
    do {
      $new = $needle[rand(0, count($needle)-1)];
    while($new != $matches[0]) {
    return $new;
  },
  $random_string);

to make sure your $needle array does not contain characters which have a special meaning in a regular expression, we call preg_quote on each item of the array before searching.

instead of doing a do{}while() loop you could also copy the array and remove the matched word (pretty much depends on the actual data: few items → copy&remove, many items → pick one random until it's different from the match)

Upvotes: 2

Related Questions