Because it is a random position, it is also possible to insert into
This place, how to solve this problem?
Can you peel the HTML tags, insert them randomly, and then restore them? I hope you can help me.
Reply to discussion (solution)
Utf-8, the test is fine.
$str = <<
<>
Test, test, test test, test test, test
Testing test test test test Test testing test test test test test Test 1 Test Test 1 Test Test 1 Test Test 1 Test test 1 Test 1 Test 1 Test test 1 Test 1 Test test 1 Test EOF; $insert =array (' Link 1 ', ' Link 2 ', ' link 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;}
Just have to have a comment.
All right, comment.
function Randominsert ($txt, $insert) {//txt content; Insert the keyword you want to insert, can be a link, an array//splits the contents into an array, each character is a value, English, Chinese, and symbols are counted as one, Utf-8 can only be split in Chinese preg_match_all ("/[\x01-\x7f]|[ \xe0-\xef][\x80-\xbf]{2}/", $txt, $match); $delay =array (); $add =0;//Gets the position index number ($delay array) that cannot be inserted, that is, the position between < > 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) {//Gets the position index value of the randomly inserted $INSERTK =INSERTK ($len-1, $delay);//loops stitch the insert data into a randomly generated index $str _ arr[$insertk].= $insert [$k]; }//Merge Insert keyword after data, stitching into a piece of content echo join ("', $str _arr);} function INSERTK ($count, $delay) {//count The range of random index values, that is, the total length of the content split into an array -1;delay the random index values that are not allowed, that is, not between < > $INSERTK =rand (0 , $count); if (In_array ($INSERTK, $delay)) {//index value cannot be at an disallowed location (that is, index values within < >) $INSERTK =insertk ($count, $delay);//recursive call until randomly inserted Index value is not in < > this index value array} return $INSERTK;}