...

View Full Version : Using array to replace text



exzrael
05-18-2007, 07:41 PM
Now, this is a tricky one for me so I hope someone know if there is a solution to this:


I'm currently using this code to search an array for a word and if found replace that word with ****. Now, can I use an array to specify both the bad word AND a word to replace it with?

My current code:


function find_replace_happy ($word){

$badwords = array(

0 => 'badword',
1 => 'badword',
2 => 'badword',
3 => 'badword',
4 => 'badword',
5 => 'badword',
6 => 'badword',
7 => 'badword'

);


$word = str_replace($badwords,'****', $word);
return $word;
}

BonRouge
05-18-2007, 07:51 PM
Maybe like this:

function find_replace_happy ($word){

$badwords = array(

0 => 'badword',
1 => 'badword',
2 => 'badword',
3 => 'badword',
4 => 'badword',
5 => 'badword',
6 => 'badword',
7 => 'badword'

);

$goodwords = array(

0 => 'goodword',
1 => 'goodword',
2 => 'goodword',
3 => 'goodword',
4 => 'goodword',
5 => 'goodword',
6 => 'goodword',
7 => 'goodword'

);

$word = str_replace($badwords,$goodwords, $word);
return $word;
}


(At least, I think that'll work).

cgibie
05-18-2007, 08:00 PM
You mean like this:



function find_replace_happy ($word){

$badwords = array(

0 => 'test',
1 => '****',
2 => 'badword',

);

$goodwords = array("happy", "sad", "yummy");

for ($i=0; $i<=count($badwords); $i++)
for ($j=$i; $j<=$i; $j++)
$word = str_replace($badwords[$i],$goodwords[$j], $word);
return $word;
}

cgibie
05-18-2007, 08:03 PM
ah I didn't know that str_replace can take the array index automatically without looping.

aedrin
05-18-2007, 08:35 PM
Yes, it can. However the methods described are not what you want.

Your original code that you posted should work.

When str_replace is fed an array of searches, and a string to replace with it will use that for every entry it finds in the search list.

From the manual: "If search is an array and replace is a string, then this replacement string is used for every value of search."



function find_replace_happy($word) {
$badwords = array(
0 => 'badword',
1 => 'badword',
2 => 'badword',
3 => 'badword',
4 => 'badword',
5 => 'badword',
6 => 'badword',
7 => 'badword'
);

return str_replace($badwords, '****', $word);
}

exzrael
05-18-2007, 08:58 PM
Thank you, got it to work :)

Fumigator
05-18-2007, 11:20 PM
BonRouge's code is a thing-a-beauty if you want to customize the replacement words so I wouldn't say it's not what you want.

Example replacement words:

farg
shizniz
durn
gull durn
fuzzy
heck
wench
kitty
son-of-unwed-mother
rooster



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum