我正在开发一个脚本,它需要一篇文章,在文章中搜索“关键字”,然后用锚链接随机替换该关键字。
我让脚本正常工作,但是我需要能够为函数循环并插入随机位置的“替换”数组。
所以第一个随机位置将获得锚链接#1。第二个随机位置将获得锚链接#2。第三个随机位置将获得锚链接#3。ETC...
我在这里找到了我的问题的一半答案: PHP replace a random word of a string
public function replace_random ($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;
}
所以我的问题是,如何更改此函数以接受 $replace 变量的数组?
编辑 我还尝试从 mt_rand 获取随机数组键,它从替换数组中输出我的替换,但它仍然只在整个内容中添加一个替换。我希望该函数为它找到的 $search 变量的每个实例选择一个“关键字”。
public function replace_random ($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;
$searchCount = count($replace);
$arrayNum = mt_rand(0, 4);
// 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[$arrayNum].substr($str, $matches[0][$match][1] + $searchLen + $offset);
$offset += $diff;
}
return $str;
}