I am developing a script that takes an article, searches the article for a "keyword" and then randomly replaces that keyword with an anchor link.
I have the script working as it should, however I need to be able to have an array of "replacements" for the function to loop through and insert at the random location.
So the first random position would get array value 1. The second random position would get array value 2. The third random position would get array value 3. etc...
public function replace_random ($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;
$searchCount = count($replace);
$arrayNum = mt_rand(0, 4);
// 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[$arrayNum].substr($str, $matches[0][$match][1] + $searchLen + $offset);
$offset += $diff;
}
return $str;
}
So my question is, How can i alter this function to accept the array for the $replace variable?