lundi 19 novembre 2018

Randomimize array inside function PHP

please help me. My function pick up keywords from string(text) and replace them with href tag, that working fine so far, but now I want (because expecting more then one keyword occurrence in string) replace each with random URL address from array, check out code to see what I want and what I get. Thank you in advance!!

$url_array = array('https://google.com/somelink1', 'https://google.com/somelink2', 'https://google.com/somelink3'); 
$search = 'Whatever text here text also this is about text';
$str = 'text';

$give_me_back_text_with_edited_links_and_random_urls = replacekeywords($str, $search, $url_array);

//What do I get?
$give_me_back_text_with_edited_links_and_random_urls = 'Whatever <a href="https://google.com/somelink2">text</a> here <a href="https://google.com/somelink2">text</a> also this is about <a href="https://google.com/somelink2">text</a>';

//What I want?
$give_me_back_text_with_edited_links_and_random_urls ='Whatever <a href="https://google.com/somelink1">text</a> here <a href="https://google.com/somelink3">text</a> also this is about <a href="https://google.com/somelink2">text</a>';


function replacekeywords($str, $search, $url_array) {

    $occurrences = substr_count(strtolower($str), strtolower($search));
    $newstring = $str;
    $match = array();

    for ($i=0;$i<$occurrences;$i++) {


        // !!!!!!!!!! how do I make $url here randomly based on $url_array?
        $url = $url_array[rand(0, count($url_array) - 1)]; 


        $match[$i] = stripos($str, $search, $i);
        $match[$i] = substr($str, $match[$i], strlen($search));
        $newstring = preg_replace("/\b([a-z]*${match[$i]}[a-z]*)\b/i","<a href='".$url."' class='link'>$0</a>",strip_tags($newstring,'<br><p>'));
    }

     return $newstring;




Aucun commentaire:

Enregistrer un commentaire