PHP隨機插入關鍵字到有HTML的內容該如何??

來源:互聯網
上載者:User
因為是隨機位置,也有可能插入到

這種地方,這個問題該怎麼解決?

能否先剝離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;}
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.