This question already has an answer here:
This is not the same as other questions asked on Stack Overflow I have tried the examples people have linked and nothing will work for me!
Prior to Asking on StackOverflow
I've googled this quite a few times, and tried many different tutorials, all of them being different from the other and making it more confusing. Using code like preg_match(), strpos() etc. and can't get it quite right.
Main Question:
I have a registration form on my site. For example, if the user were to sign up with a username like Bad or BadWord, I want it to stop them from doing so.
I have an array of bad words:
$badWords = array('some', 'bad', 'words');
My username variable is:
$username
I want to do a check, for example, if Bad or BadWords contains a word from the array, if it does then it will echo 'bad word detected!'
Pseudo code for example:
if ($username contains $badWords) {
echo 'bad word detected!';
}
I don't have the greatest knowledge of PHP as I only began to learn it a few months ago, that is why I am asking for help.
Thanks!
</div>
The simplest way would be to loop through the array with a for loop, and then check if each index exists inside the string. That can be achieved like so:
$badWords = array('fk', 'st', 'ct', 'bd', 'dk');
$containsBadWord = false;
foreach ( $badWords as $badWord ) {
if ( stripos($username, $badWord) ) {
$containsBadWord = true;
break; //We do this just to save a few loops where unneccesary
}
}
if ( $containsBadWord ) {
echo 'That username contains a word or words that are undesirable. Please pick a different username.';
} else {
echo 'That username does not contain a word or words that are undesirable, and you can use that.';
//Provided that the username passes other checks such as whether it has not been used before
}
I would suggest using stripos in this context instead of strpos, due to the case insensitive nature of stripos. Also, if you do not understand the foreach, click the link to learn more about it on the PHP website. The foreach behaves the same here as a for loop as below:
$count = count($badWords);
for ( $i=0; $i<$count; $i++ ) {
if ( stripos($username, $badWords[$i]) ) {
$containsBadWord = true;
break; //We do this just to save a few loops where unneccesary
}
}