php - PHP替换字符串中的随机词

标签 php string random replace word

我想替换一个随机单词,其中一个字符串中包含多个单词。

假设字符串是

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


假设我想用红色替换蓝色一词,但在随机位置仅2次。

所以完成一个功能后,输出可能像

I like red, blue is my favorite colour because red is very nice and blue is pretty


另一个可能是

I like blue, red is my favorite colour because blue is very nice and red is pretty


因此,我想多次替换相同的单词,但每次都在不同的位置。

我想到使用preg_match,但是没有选择peing替换的单词的位置也是随机的。

有人知道如何实现这一目标吗?

最佳答案

就像我不愿意在正则表达式上使用正则表达式一样,为了保证正好n个替换,我认为它可以在这里有所帮助,因为它允许轻松使用array_rand(),它确实可以完成您的工作想要-从不确定长度的列表中选择n个随机项目(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

关于php - PHP替换字符串中的随机词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10704460/

相关文章:

php - 如何在 Python 中加密字符串并在 PHP 中解密相同的字符串?

php - 重新创建对象或将其存储在 session 变量中是否更快?

javascript - 如何向现有的 onClick 视频事件添加随机、连续的视频自动播放?

swift - SpriteKit - 在随机位置创建而不重叠

php - mysql unhex() 不能在 linux 服务器上运行?

php - MYSQL IF(expr1,expr2,expr3) 但我不想要任何 expr3(如果 expr3 则不输出任何内容

java - 如何用不同的 Unicode 字符构建最长的字符串

c++ - C++二进制数字数组转换为int值

c - 查找字符串中的子字符串数

c++ - 尝试在C++中生成特定范围内的随机数