Question: I want to replace one random word of which are several in a string.

So let's say the string is

```
$str = 'I like blue, blue is my favorite colour because blue is very nice and blue is pretty';

```

And let's say I want to replace the word blue with red but only 2 times at random positions.

So after a function is done the output could be like

```
I like red, blue is my favorite colour because red is very nice and blue is pretty

```

Another one could be

```
I like blue, red is my favorite colour because blue is very nice and red is pretty

```

So I want to replace the same word multiple times but every time on different positions.

I thought of using preg\_match but that doesn't have an option that the position of the words peing replaced is random also.

Does anybody have a clue how to achieve this?

Answer: 
Well, you could use this algorithm:

1. calculate the random amount of times you want to replace the string
2. explode the string into an array
3. for that array replace the string occurence only if a random value between 1 and 100 is % 3 (for istance)
4. Decrease the number calculated at point 1.
5. Repeat until the number reaches 0.
```
<?php
$amount_to_replace = 2;
$word_to_replace = 'blue';
$new_word = 'red';

$str = 'I like blue, blue is my favorite colour because blue is very nice and blue is pretty';

$words = explode(' ', $str); //convert string to array of words
$blue_keys = array_keys($words, $word_to_replace); //get index of all $word_to_replace

if(count($blue_keys) <= $amount_to_replace) { //if there are less to replace, we don't need to randomly choose.  just replace them all
    $keys_to_replace = array_keys($blue_keys);
}
else {
    $keys_to_replace = array();
    while(count($keys_to_replace) < $amount_to_replace) { //while we have more to choose
        $replacement_key = rand(0, count($blue_keys) -1);
        if(in_array($replacement_key, $keys_to_replace)) continue; //we have already chosen to replace this word, don't add it again
        else {
            $keys_to_replace[] = $replacement_key;
        }
    }
}

foreach($keys_to_replace as $replacement_key) {
    $words[$blue_keys[$replacement_key]] = $new_word;
}

$new_str = implode(' ', $words); //convert array of words back into string
echo $new_str."\n";
?>

```

N.B. I just realized this will not replace the first blue, since it is entered into the word array as "blue," and so doesn't match in the array\_keys call.