Array Help...
Posted: Tue Aug 11, 2009 7:45 am
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
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
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.
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]";
Code: Select all
//Just a demo or a test
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);