因為是隨機位置,也有可能插入到
這種地方,這個問題該怎麼解決?
能否先剝離HTML標籤,隨機插入後,再還原呢?希望大家幫幫我。
回複討論(解決方案)
utf-8下測試沒問題
$str = <<試測試測試,測試測試測試測試測試測試測試,測試測試測試,測試測
試測試測試測試測試測試測試測試測試測試,測試測試測試測試測試測試測試1測試,測試1測試測試1測試測試1測試測試1測試,測試1測試測試1測試測試1測試,測試1測試測試1測試EOF; $insert=array('連結1','連結2','連結3');echo randomInsert($str,$insert);function randomInsert($txt,$insert){preg_match_all("/[\x01-\x7f]|[\xe0-\xef][\x80-\xbf]{2}/", $txt, $match);$delay=array();$add=0;foreach($match[0] as $k=>$v){if($v=='<') $add=1;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);$str_arr[$insertk].=$insert[$k];}echo join('',$str_arr);}function insertK($count,$delay){$insertk=rand(0,$count);if(in_array($insertk,$delay)){$insertk=insertK($count,$delay);}return $insertk;}
要有注釋就好了
好吧,注釋
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=='<') $add=1; 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]; }//合并插入 關鍵詞後的資料,拼接成一段內容 echo 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;}