Page 1 of 1

preg_replace

Posted: Thu Apr 21, 2005 5:30 am
by shiznatix
ok i have this running as a bad word filter

Code: Select all

$bad_file = file_get_contents('badwords.txt');
$bad_words = explode(',', $bad_file);
foreach($bad_words as $bad){
	$bad = trim($bad);
	$check = strpos($message, $bad);
	if ($check != false){
		$len = strlen($bad);
		for($i=0; $i<$len; $i++){
			$replace .= '*';
		}
		$message = preg_replace($bad, $replace, $message);
		unset($replace);
	}
}
but i keep getting the error message
Warning: Delimiter must not be alphanumeric or backslash in /home/wesmok2/public_html/shizMsg/process.php on line 100
after it finds 1 match. what does that mean anyway? the string only contains letters and spaces.

d11wtq | Shiz, please read the sticky about posting code with line offsets :)

Posted: Thu Apr 21, 2005 6:01 am
by Chris Corbyn
The delimiters in RegExp are usually just forward slashes /pattern/

In the above you could have any character.

You can use #pattern# instead however...

Try:

Code: Select all

$bad_file = '#'.file_get_contents('badwords.txt').'#';

Posted: Thu Apr 21, 2005 6:24 am
by shiznatix
aye sorry i didnt know about the line thing with php code thing but thats perdy cool.

i figured out where the problem was. just did

Code: Select all

$bad = '/'.$bad.'/';
right before the preg_match and it worked perfectly.

Posted: Thu Apr 21, 2005 12:41 pm
by vigge89
You could also separate the bad words by an | (vertical bar). The you wouldn't have to call preg_replace for each word:

Code: Select all

$message = preg_replace ('#('.file_get_contents ('bad_words.txt').')#ie', "str_repeat ('*', strlen('\\1'))", $message);
the preg e-modifier makes the function parse the replacement as PHP code, str_repeat() repeats a string a number of times (= length of the word).

Posted: Thu Apr 21, 2005 2:20 pm
by Todd_Z
Just another example of how php is divine - all that coding can be replaced with one line. Amazing.