我想替换一个字符串中的一个随机字。
所以让我们说字符串是
$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替换的单词的位置也是随机的。
有没有人知道如何实现这个目标?
答案 0 :(得分:3)
就像我厌恶使用正则表达式来表达它非常简单的东西一样,为了保证完全 n 取代我觉得它可以帮到这里,因为它允许使用array_rand()
,它完全符合您的要求 - 从不确定长度列表中选择 n 随机项目(改进)。< / p>
<?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);
答案 1 :(得分:2)
echo preg_replace_callback('/blue/', function($match) { return rand(0,100) > 50 ? $match[0] : 'red'; }, $str);
答案 2 :(得分:1)
嗯,你可以使用这个算法:
答案 3 :(得分:0)
<?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。我刚刚意识到这不会取代第一个蓝色,因为它以“蓝色”的形式输入到单词数组中,因此在array_keys调用中不匹配。