Page 1 of 1

preg_match with arrays

Posted: Tue Sep 21, 2004 10:33 pm
by hawleyjr
I have a function that accepts a string (username) and determines if the string contains any 'forbidden' words. The code works fine. I just want to do this without using an foreach loop. Any thoughts?

Code: Select all

<?php
function checkForForbiddenWords($username){
$A_FORBIDDEN_WORDS = array('BADWORD1'=>1,
			'BADWORD2'=>1,
			'BADWORD3'=>1,
			'BADWORD4'=>1,
			'BADWORD5'=>1);
	
	
foreach($A_FORBIDDEN_WORDS as $ak => $val){
	
	if(preg_match("/$ak/", $username))
		return FALSE;

}

return TRUE;
}
?>

Posted: Wed Sep 22, 2004 12:15 am
by feyd
compacting the array's keys (as you have them) into a matching group would work.

basically:

Code: Select all

$look = implode('|',array_keys($A_FORBIDDEN_WORDS));
return preg_match('#(' . $look . ')#i', $username);
however, you have to be careful about the badwords list containing any leading or trailing spaces and regular expression symbols ;)

in_array

Posted: Wed Sep 22, 2004 2:58 am
by phpScott
you could also use in_array()

Code: Select all

<?php
if(!in_array($username, $A_FORBIDDEN_WORDS))
  echo "username is fine";
else
  echo "please change username";
?>
in_array looks for the needle -> in the haystack.

Re: in_array

Posted: Wed Sep 22, 2004 6:11 am
by John Cartwright
phpScott wrote:you could also use in_array()

Code: Select all

<?php
if(!in_array($username, $A_FORBIDDEN_WORDS))
  echo "username is fine";
else
  echo "please change username";
?>
in_array looks for the needle -> in the haystack.
What is the username contains spaces, you would have to explode the username.

Preg_match is the way to go

Posted: Wed Sep 22, 2004 8:49 am
by m3mn0n
What's wrong with a foreach loop? Just curious...

your right

Posted: Wed Sep 22, 2004 8:56 am
by phpScott
your right Phenom.
I have only used in_array on info that I am postive about and not random user data.

Posted: Wed Sep 22, 2004 6:58 pm
by hawleyjr
Sami wrote:What's wrong with a foreach loop? Just curious...
Nothing, especially in the case I only have about 10 curse words I don't want people to use in conjunction with their username. Its one of those things where I know it can be done without a loop I just don't know how. Thanks all for the pointers.

Posted: Wed Sep 22, 2004 7:29 pm
by John Cartwright
What's wrong with feyds suggestions?