...

View Full Version : how to replace one phrase with another using arrays



needsomehelp
11-05-2012, 08:38 AM
I wish to filter inappropriate words using an array method.
I currently have...

$badwords = array("'word1'i", "'word2'i", "'word3'i"
);

That I have in a function that basically returns, good or bad, and if bad the page says so and stops the phrase being added until they change it.


So lets say someone enters in the field..
'I am a badword'
I wish to use an array method that will replace the badword with something else.

like so...


badword1 to goodword1
badword2 to goodword2

It would also need to be case insensitive.

Redcoder
11-05-2012, 01:52 PM
There's no array function in PHP that does that - simply replacing a value in an array if a pre-defined string is found.

You'll just have to use a lo0p to do that for you. E.g a for loop

This is kinda crude but it's along the kines for what you should use


for($i=0; $i<=count($your_array))
{

if($your_array[$i] == 'string1' || $your_array[$i] == 'string1' || $your_array[$i] == 'string1'){

die("Bad word used');

}

}

Fou-Lu
11-05-2012, 02:28 PM
You can use str_replace for this:


$aBadWords = array('badword1', 'badword2');
$aGoodWords = array('goodword1', 'goodword2');

print str_replace($aBadWords, $aGoodWords, $input);

str_ireplace can be done case insensitively. If you need more complex checks such as containing a phrase, then a pcre with preg_replace would be easier.

needsomehelp
11-05-2012, 08:01 PM
This one looks like it will do the job I need it for, thanks.

I had been racking my brain for a way to use an array that contains the badword and good work so the script would have checked for the first and replaced with the associated good word. but this method will work for me i hope.

thanks again.


You can use str_replace for this:


$aBadWords = array('badword1', 'badword2');
$aGoodWords = array('goodword1', 'goodword2');

print str_replace($aBadWords, $aGoodWords, $input);

str_ireplace can be done case insensitively. If you need more complex checks such as containing a phrase, then a pcre with preg_replace would be easier.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum