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: 
Much as I am loathed to use regex for something which is on the face of it very simple, in order to **guarantee exactly *n* replaces** I think it can help here, as it allows use to easily use [`array_rand()`](http://php.net/manual/en/function.array-rand.php), which does exactly what you want - pick *n* random items from a list of indeterminate length (**IMPROVED**).

```
<?php

    function replace_n_occurences ($str, $search, $replace, $n) {

        // Get all occurences of $search and their offsets within the string
        $count = preg_match_all('/\b'.preg_quote($search, '/').'\b/', $str, $matches, PREG_OFFSET_CAPTURE);

        // Get string length information so we can account for replacement strings that are of a different length to the search string
        $searchLen = strlen($search);
        $diff = strlen($replace) - $searchLen;
        $offset = 0;

        // Loop $n random matches and replace them, if $n < 1 || $n > $count, replace all matches
        $toReplace = ($n < 1 || $n > $count) ? array_keys($matches[0]) : (array) array_rand($matches[0], $n);
        foreach ($toReplace as $match) {
            $str = substr($str, 0, $matches[0][$match][1] + $offset).$replace.substr($str, $matches[0][$match][1] + $searchLen + $offset);
            $offset += $diff;
        }

        return $str;

    }

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

    $search = 'blue';
    $replace = 'red';
    $replaceCount = 2;

    echo replace_n_occurences($str, $search, $replace, $replaceCount);

```

[See it working](http://codepad.viper-7.com/tcpRsG)
```
echo preg_replace_callback('/blue/', function($match) { return rand(0,100) > 50 ? $match[0] : 'red'; }, $str);

```