replace a random word of a string with a random replacement

Posted by tpickett on Stack Overflow See other posts from Stack Overflow or by tpickett
Published on 2012-11-12T22:57:02Z Indexed on 2012/11/12 22:59 UTC
Read the original article Hit count: 237

Filed under:
|
|
|
|

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 anchor link #1. The second random position would get anchor link #2. The third random position would get anchor link #3. etc...

I found half of the answer to my question here: PHP replace a random word of a string

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;

    // 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;

}

So my question is, How can i alter this function to accept an array for the $replace variable?

© Stack Overflow or respective owner

Related posts about php

Related posts about arrays