PHP 替换字符串中的一个随机单词 [英] PHP replace a random word of a string
问题描述
我想替换一个字符串中的一个随机单词.
I want to replace one random word of which are several in a string.
所以假设字符串是
$str = 'I like blue, blue is my favorite colour because blue is very nice and blue is pretty';
假设我想用红色替换蓝色这个词,但只在随机位置替换 2 次.
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
另一个可能是
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.
我想过使用 preg_match ,但没有选项 peing 替换的单词的位置也是随机的.
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?
推荐答案
就像我讨厌将正则表达式用于表面上非常简单的事情一样,为了保证完全n 替换 我认为它可以在这里有所帮助,因为它允许使用轻松使用 array_rand()
,它完全符合您的要求 - 从不确定长度的列表中选择 n 个随机项目(改进).
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);
这篇关于PHP 替换字符串中的一个随机单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!