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