我想更换一个随机字这些都是在一个字符串几个。
所以我们可以说该字符串
$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个随机物品。
<?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);
看到它的工作
echo preg_replace_callback('/blue/', function($match) { return rand(0,100) > 50 ? $match[0] : 'red'; }, $str);
<?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";
?>
注:我刚刚意识到这不会替换第一个蓝色的,因为它是进入字阵“蓝色”等不匹配在array_keys调用。