【发布时间】:2012-11-12 22:57:02
【问题描述】:
我正在开发一个脚本,它获取一篇文章,在文章中搜索“关键字”,然后随机用锚链接替换该关键字。
我的脚本可以正常工作,但是我需要能够有一个“替换”数组,以便函数循环遍历并插入到随机位置。
所以第一个随机位置将获得锚链接 #1。 第二个随机位置将获得锚链接#2。 第三个随机位置将获得锚链接#3。 等等……
我在这里找到了我问题的一半答案: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;
}
【问题讨论】:
-
这是基本的算法,不是编程问题……你只尝试过吗?
-
是的,我曾尝试将数组与该函数一起使用,但它什么也没有替换...在旁注中,我看不出这是如何不清楚或无用的。我已经研究了一个星期!这就是为什么我问社区...为什么负面代表?
-
已编辑帖子以显示为解决该问题所做的尝试,希望这使其成为编程问题?
标签: php arrays string function preg-match-all