Link to home
Start Free TrialLog in
Avatar of array007
array007

asked on

Badwords filter, finding only "whole word"

I have the following that works fine
But it finds also false badword within a longer word
Example:
I need to remove "cha"
it will rem it out of" any words cha and more"
but also in this form
"experts exchange" where if finds cha, which is indeed not OK
function unallowed($reply) {
	include($_SERVER['DOCUMENT_ROOT']."/badwords/bw.php");
	 
	$star = "*";
	
	for ($i = 0; $i < sizeof($badwords); $i++) {
		$censored = substr($badwords[$i], 0,1);
		for ($x = 1; $x < strlen($badwords[$i]); $x++) $censored .= $star;
		$reply = str_replace($badwords[$i], $censored, $reply);
	}
	return $reply;
}	

And
bw.php looks like this:
<?php
$badwords = 
array (
'zzzzz',
etc.....

Open in new window

Avatar of Chad Haney
Chad Haney
Flag of United States of America image

Use regex with preg_replace, if you want to censor the words out.  Or use preg_match to just get a true/false if the word is in the haystack.

http://php.net/manual/en/function.preg-replace.php
http://php.net/manual/en/function.preg-match.php
Avatar of array007
array007

ASKER

Thanks
But regex is not my forte
could you show me the way with preg_replace?
regards
Like this.
<?php
$string = 'Experts Exchange.';
$pattern = '/cha/';
$replacement = '###';
echo preg_replace($pattern, $replacement, $string);

//Echos  Experts Ex###nge
?>

Open in new window

You can also do it as an array
<?php
$string = 'Experts Exchange has a lot of answers for questions.';
$patterns = array();
$patterns[0] = '/answers/';
$patterns[1] = '/for/';
$patterns[2] = '/questions/';
$replacements = array();
$replacements[0] = 'problems';
$replacements[1] = 'to';
$replacements[2] = 'solve';
echo preg_replace($patterns, $replacements, $string);
//Echos  Experts Exchange has a lot of problems to solve.
?>

Open in new window

Thanks,
but it does not resolve my quest, the first solution is getting the same result as what I do know.
I am looking for it not to pick up "cha" in exchange but to pick it up in a str like: this is cha a str"
as a whole word only

And the other solution I am not up to adapt it
as I did not find a way to make my array working as the pattern
it looks like:
<?php
$badwords =
array (
'zzzzz',
etc.....
ASKER CERTIFIED SOLUTION
Avatar of Chad Haney
Chad Haney
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks works a treat!
I just needed, as I got a var error,
to declare before the concat
wordlist as empty
$wordlist='';