PHP随机替换字符串的函数
这个函数会全部随机替换,注意preg_replace_callback函数的参数
preg_replace_callback ( mixed $pattern , callable $callback , mixed $subject [, int $limit = -1 [, int &$count ]] )
使用方法
$text = "Welcome to [city]. I want [city] to be a random version each time. [city] should not be the same [city] each time.";
$keyword = "[city]";
$values = array("Orlando", "Dallas", "Atlanta", "Detroit", "Tampa", "Miami");
$result = preg_replace_callback('/' . preg_quote($keyword) . '/',
function() use ($values){ return $values[array_rand($values)]; }, $text);注意:以下的函数不适用于特殊字符的替换:
/**
* @param 原始字符串
* @param 原始字符
* @param 替换字符
* @param 替换次数
* @return 替换后的字符串
*/
function replace_n_occurrences ($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 $str."<br>"; echo replace_n_occurrences($str, $search, $replace, $replaceCount);