Search code examples
phparraysstringsubstringcontains

How to block form submissions if the message field contains certain words (PHP)?


I want to prevent the contact form from submission if the message field contains certain words. I used one, two and three as an example:

//Prevent the form from submission if it contains one, two, or three
$needle = ['one', 'two', 'three'];
if (stripos($message, $needle) !== false) {
    echo "$message contains $needle";
}

This did not work for me. However, I tested this with one word only and it worked:

if (stripos($message, 'one') !== false) {
    echo 'invalid message format';
}

How can I check on multiple words in a message in PHP if the above array is not working?


Solution

  • You need to use for loop.

    $needle_arr = ['one', 'two', 'three'];
    $included = [];
    
    foreach($needle_arr as $needle)
      if (stripos($message, $needle) !== false) {
          $included []= $needle;
      }
    
    if(count($included) > 0)
      echo "$message contains ".implode(", ", $included);