PHP replace a random word of a string

做~自己de王妃 提交于 2019-12-11 02:53:39

问题


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?


回答1:


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(), 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




回答2:


echo preg_replace_callback('/blue/', function($match) { return rand(0,100) > 50 ? $match[0] : 'red'; }, $str);



回答3:


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.



回答4:


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



来源:https://stackoverflow.com/questions/10704460/php-replace-a-random-word-of-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!