Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

regular expression with array

Status
Not open for further replies.

elck

Programmer
Apr 19, 2004
176
NL
I would like to replace any occurance of a word from an array:

$afk[1]="ADABIP";
$afk[2]="COCSEP";
$afk[3]="ADADEC";

with a link to a relevant page like this:

The beetle ADABIP looks a lot like COCSEP except for the number of dots.

Would become:

The beetle <a href=pag.php?srt=ADABIP>ADABIP<a> looks a lot like <a href=pag.php?srt=COCSEP>COCSEP</a> except for the number of dots.

I tried:
$b=preg_replace ($afk, '<a href=pag.php?srt=$1>$1</a>', $b);

I also tried putting / / around the items in the string,
but it still does not work.

Any ideas? I admit I'm not good at this.

 
Why would you use preg_replace()?

Well.. You are treating $afk as a variable, and not an array. You would have to use foreach() to work with arrays.

Here is the script you probably want. Foreach statements go through complete arrays. Each array key is placed in $key, and its value is placed in $value. It is a loop, so it goes through the whole array. Replace the third line of the script, though. Since I don't know what you're making, I can't input the exact script you need.

Code:
foreach($afk as $key => $value) {
$b = str_replace ($afk, '<a href=pag.php?srt=$1>$1</a>', $b);
}
}
 
huh? where does your proposal fill $1???
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top