[英]PHP replace a random word of a string
我想替換一個隨機單詞,其中一個字符串中包含多個單詞。
假設字符串是
$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替換的單詞的位置也是隨機的。
有人知道如何實現這一目標嗎?
就像我不喜歡使用regex來處理表面上很簡單的事情一樣,為了保證正好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";
?>
注意,我剛剛意識到這不會替換第一個藍色,因為它以單詞“ blue”輸入到單詞數組中,因此在array_keys調用中不匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.