preg_replace

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

preg_replace

Post 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 :)
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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').'#';
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post 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.
User avatar
vigge89
Forum Regular
Posts: 875
Joined: Wed Jul 30, 2003 3:29 am
Location: Sweden

Post 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).
Last edited by vigge89 on Fri Apr 22, 2005 12:46 am, edited 1 time in total.
User avatar
Todd_Z
Forum Regular
Posts: 708
Joined: Thu Nov 25, 2004 9:53 pm
Location: U Michigan

Post by Todd_Z »

Just another example of how php is divine - all that coding can be replaced with one line. Amazing.
Post Reply