Page 1 of 1

Array Help...

Posted: Tue Aug 11, 2009 7:45 am
by lawrenceagan
I have racked my head on this for hours and can not seem to get something that works. What I am trying to do is build a token system, so I can add custom strings into other strings by wrapping them in [brackets]. The code I have below works, but if I have 2 instances of the same token it will sometimes add the same value twice.

Take the example [TEST], which has the values of:
1. test
2. demo
3. example

and the string

Code: Select all

 
$string="Just a [TEST] or a [TEST]";
 
if I grab a random value for the token [TEST] and the first instance is "demo" and the 2nd is "test" then the result would be

Code: Select all

 
//Just a demo or a test
 
But if it grabs the same word twice, that is no good. How in the world would I prevent duplicate values?

My code is sorta choppy, so if anyone knows a better way please let me know.

Code: Select all

 
public function getData($token){
$s="SELECT * FROM `ads_tokens` WHERE `token_name` = '".$token."' ORDER BY RAND()";
$q=mysql_query($s);
while($d=mysql_fetch_assoc($q)){
    $token = $d['token_value'];
    }
$line = split("\n", $token);
$num =  array_rand($line,1);
    if($line[$num]==""){
        $num = $num-1;
    }
return $line[$num];
}
 
public function processAd($string){
    preg_match_all("|\[(.*)\]|U",$string,$token,PREG_SET_ORDER);
    $num = count($token)-1;
    $i=0;
    while($i<=$num){
        $replacement[$i]=$this->getData($token[$i][1]);
        $pattern[$i]="/\[".$token[$i][1]."\]/";
        $final =  preg_replace($pattern, $replacement, $string, 1);
        $i++;
        }
    return $final;
}
$string="Just a [TEST] or a [TEST]"
$token=new Token;
print $token->processAd($string);
 

Re: Array Help...

Posted: Tue Aug 11, 2009 10:17 am
by aceconcepts
Could you not remove duplicate values from your array before outputting them?

Re: Array Help...

Posted: Tue Aug 11, 2009 1:21 pm
by lawrenceagan
No, because there are never any duplicates from the original array, duplicates come about from multiple instances of the array

Re: Array Help...

Posted: Tue Aug 11, 2009 1:41 pm
by requinix
What should happen if you have more [TEST]s than tokens?

Re: Array Help...

Posted: Tue Aug 11, 2009 4:53 pm
by lawrenceagan
Anything wrapped in [BRACKETS] would be a token. So lets say I had a token named [TEST] with 3 values and I have 4 instances of [TEST] in my string I would have to loop back through and grab a reoccurring value. Although I do not anticipate this scenario, but that is a good point that I completely overlooked.