PHP实现文本中字符串的随机插入、替换等处理
非常简单的实现方法,思路是将目标字符串提取分割开,重新组合合并
$myString = '<p>I like blue, </p><p>blue is my favorite</p> <p>colour because blue is very nice and blue is pretty</p>'; $myVar = '123<p>'; $words = explode('<p>', $myString); // split the string into words $index = rand(0, count($words) - 1); // select a random index $words[$index] = $myVar; // replace the word at the random position //$words[$index] = $myVar . $words[$index]; // insert the word at the random position $myString = implode('<p>', $words); // merge the string back together from the words echo $myString;
或者高级一点替换数组
$myString = '<p>I like blue, </p><p>blue is my favorite</p> <p>colour because blue is very nice and blue is pretty</p>'; $words = explode('<p>', $myString); $inserted = array( '123</p>' ); // not necessarily an array, see manual quote array_splice($words, array_rand($words), 0, $inserted ); // splice in at position 3 $myString = implode("<p>", $words); echo $myString;
如果要使用起来更方便可以封装一下变成这样,参数依次是:原始字符
,查找字符
,替换字符
,起始位置
function insert_random_text($str, $search, $replace, $start=0){ $words = explode($search, $str); // split the string into words $index = rand($start, count($words) - 1); // select a random index $words[$index] = $replace; // replace the word at the random position #option1 替换字符 //$words[$index] = $myVar . $words[$index]; // insert the word at the random position #option2 插入字符,注意插入目标搜索字符串的前或后位置可调整 $body = implode($search, $words); // merge the string back together from the words return $body; }
另外一个实现随机替换字符串的函数,参数分别是:字符串
,目标字符
,替换字符
,替换次数
,不过函数无法实现特殊字符的筛选
/** * @param 原始字符串 * @param 目标字符 * @param 替换字符 * @param 替换次数 * @return 字符串 */ 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 = 1; echo replace_n_occurences($str, $search, $replace, $replaceCount);