PHP randomly inserts keywords into HTML content. how can this problem be achieved? Because it is a random location, it is also possible to insert
How can this problem be solved?
Can I strip the HTML tag and insert it randomly before restoring it? Hope you can help me.
Reply to discussion (solution)
Test in UTF-8
$ Str = <
Test, test, test
Test, test 1 test, test 1 test 1 test 1 test 1 test, test 1 test 1 test 1 test 1 test 1 test 1 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 comment it out.
Okay, comment
Function randomInsert ($ txt, $ insert) {// txt content; insert the keyword to be inserted, which can be a link, array // split the content into an array, each character is a value, english, Chinese, and symbols are counted as one, you can only split preg_match_all ("/[\ x01-\ x7f] | [\ xe0-\ xef] [\ x80-\ xbf] {2}/" in UTF-8 }/", $ txt, $ match); $ delay = array (); $ add = 0; // Obtain the index number of a location that cannot be inserted ($ delay array ), 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) {// Obtain the random insert location index value $ insertk = insertK ($ len-1, $ delay ); // concatenate the insert data into the randomly generated index $ str_arr [$ insertk]. = $ insert [$ k];} // merge the inserted keyword data and splice it 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 after the content is split into an array-1; random index values not allowed by delay, that is, it cannot be between <> $ insertk = rand (0, $ count); if (in_array ($ insertk, $ delay )) {// The index value cannot be at an unsupported position (that is, the index value within <>) $ insertk = insertK ($ count, $ delay); // recursive call, until the randomly inserted index value is not in the <> index value array} return $ insertk ;}