我想替换一个随机单词,其中一个字符串中包含多个单词。
假设字符串是
$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/