php随机关键词,php实现向含html文本内容随机位置插入关键词

$str = <<

这是一段测试内容

随机位置插入关键词

支持插入html代码

EOF;

$insert=array('链接1','链接2','链接3');

echo randomInsert($str,$insert);

function randomInsert($txt,$insert){//txt 内容;insert要插入的关键字,可以是链接,数组

//将内容拆分成数组,每个字符都是一个value,英文,中文,符号都算一个,只能在utf-8下中文才能拆分

preg_match_all("/[\x01-\x7f]|[\xe0-\xef][\x80-\xbf]{2}/", $txt, $match);

$delay=array();

$add=0;

//获取不能插入的位置索引号($delay 数组),也就是< > 之间的位置

foreach($match[0] as $k=>$v){

if($v=='

if($add==1) $delay[]=$k;

if($v=='>') $add=0;

}

$str_arr=$match[0];

$len=count($str_arr);

foreach($insert as $k=>$v){

//获取随机插入的位置索引值

$insertk=insertK($len-1,$delay);

//循环将insert数据 拼接到 随机生成的索引

$str_arr[$insertk].=$insert[$k];

}

//合并插入 关键词后的数据,拼接成一段内容

return join('',$str_arr);

}

function insertK($count,$delay){//count 随机索引值范围,也就是内容拆分成数组后的总长度-1;delay 不允许的随机索引值,也就是不能在 < > 之间

$insertk=rand(0,$count);

if(in_array($insertk,$delay)){//索引值不能在 不允许的位置处(也就是< > 之内的索引值)

$insertk=insertK($count,$delay);//递归调用,直到随机插入的索引值不在 < > 这个索引值数组中

}

return $insertk;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值