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: 
```
echo preg_replace_callback('/blue/', function($match) { return rand(0,100) > 50 ? $match[0] : 'red'; }, $str);

```
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.