Home  >  Article  >  Backend Development  >  用随机数轮换文章中的多个网址,要求每个网址后面的随机数都不同

用随机数轮换文章中的多个网址,要求每个网址后面的随机数都不同

WBOY
WBOYOriginal
2016-06-13 13:23:42766browse

用随机数替换文章中的多个网址,要求每个网址后面的随机数都不同
数据库里面有很多文章。文章里面有很多网址
我想在网址后面添加随机数,但是每个网址后面的随机数都要是不同的。

我写了一个 能替换,但是结果是替换后每个网址后面的随机数都一样了

for($i=1;$i$duoyu=rand(1,111);
$res->fn_sql("update content set body=replace(body,'com','com$duoyu') where aid='$i'");
}

请大侠帮忙

------解决方案--------------------
上面的代码还不能保证在一次循环中生成的随机数都是唯一的,要是需求比较严格的话,代码还需要修改一下:

PHP code
function addRandNumber($matches) {
    global $ar;
    $n = rand(1, 111);
    while(in_array($n, $ar)) $n = rand(1, 111);
    $ar[] = $n;
    return $matches[1].$n;
}
$body = "url_com
url_com
url_com"; $ar = array(); $body = preg_replace_callback( "|(com)+?|", 'addRandNumber', $body);
------解决方案--------------------
jquery实现吧。很简单的。

$("A").each(function(index, obj)
{
$(obj).attr("href", $(obj).attr("href")+"?rand="+Math,random);
})
------解决方案--------------------
探讨

我算是看出来了,csdn高手总是那么几个
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn