john
john

Reputation: 1273

How to compare content form textarea with values from array with php?

I want to check if the content from a text area contains certain "bad words". I read the content from the textarea with $_POST['message'] This is my textarea:

<textarea class="form-control" name="message" placeholder="MESSAGE"></textarea>                             

All the bad words are in an array:

// read bad words into array
$blacklistfile = 'blacklist/badwords.txt';
$blacklistarray = file($blacklistfile, FILE_IGNORE_NEW_LINES);

To check if the content of $_POST['message'] contains any of these bad words, i thought: put all the content of $_POST['message'] into an array and compare these arrays.

I tried in the textarea [] after the message:

<textarea class="form-control" name="message[]" placeholder="MESSAGE"></textarea>   

and:

$usermessage = $_POST['message'];
print_r($usermessage);

But print_r() gives me no output

So how can i put the content of the textarea into an array??

Or: maybe there are other possibilities to achieve this?

Upvotes: 0

Views: 271

Answers (1)

LightNight
LightNight

Reputation: 851

Your textarea will submit one string

<textarea class="form-control" name="message" placeholder="MESSAGE"></textarea>

On server you must explode this string on spaces to get array of words

$textareaValue = $_POST['message'];
$wordsToCheck = explode(" ",$textareaValue);

Also you can filter unique words to avoid duplicate iteration

$wordsToCheck = array_unique($wordsToCheck); 

After that, you can compare each textarea words to badlist

foreach ($wordsToCheck as $word){
    if(in_array($word, $blacklistarray)){
        //word is bad
    }else{
        //it's ok
    }
}

Did I understood your question correctly?

Upvotes: 2

Related Questions