Jump to content

Check if text contains certain words


lip9000

Recommended Posts

Basically I want to check a bunch of text for certain swear words, and if it contains at least 1 word, then throw out an error. All I can find on the net is replacing text with other text, I dont want to replace it, I just want to see if it's there.

 

So maybe have an array full of swear words, then after the form is submitted check if that text contains any of those words, if yes, then do something.

 

Thanks heaps in advance!

Link to comment
Share on other sites

No, you could do something like

 

<?php
function wordsExist(&$string, $words) {
    foreach($words as &$word) {
        if(stripos($string, $word) !== false) {
            return true;
        }
    }
    return false;
}

$string = 'Find the word swear.';
if (wordsExist($string, array('swear','this','that','another','badword','andthis'))) {
    echo 'I found one of the words!';
}
?>

Link to comment
Share on other sites

You can do this if you want:

 

// Array of Bad words
$words = array('fuck','shit','damn','ass');
// Array of extention to words
$exten = array('','ed','ing','s');
// Input string
$str = 'this is a fucking sentence';
// Create an array from input
$string = explode(' ',strtolower($str));
// Create a new array for all combinations of swear words
$wordList = array();
// Add all combinations to the new array
foreach($words as $word){
   foreach($exten as $ext){
      $wordList[] = $word.$ext;
   }
}
// Loop through each input word, and check if it is a bad word or not
// FALSE = Good Words
// TRUE = Bad Words
$badWord = FALSE;
foreach($string as $s){
   if(in_array($s, $wordList)){
      $badWord = TRUE;
   }
}
// Do something if output is good or bad in this case display a message
if($badWord)
   echo 'This input contains inapropriate content';
else
   echo 'This is valid input!';

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.