0

Hi please help me I am using this code to filter some words but the the problem is it doesn't match the exact word and in stead it just blocks words that contain the letters from my word.

For example: ".com" I type commander and the word gets blocked please help.

$badwords = explode('|', 'http|www|.com');
    foreach($badwords as $badword)
    {

        if(preg_match("/$badword/", $post->data['message'], $match))
        {

            $post->errors['badwords']['error_code'] = "Warning message goes here";

        }
    }
Andrey
  • 1,476
  • 1
  • 11
  • 17

2 Answers2

0

The line you want is likely

preg_match("/\b$badword\b/i", $post->data['message'], $match))

The \b indicates a letter which cannot be used to form a word (see here). This prevents com from matching commander or datacom. The i at the end makes the search case-insensitive.

Also, keep in mind that using .com as one of your badwords may not have the effect you want. The period character (.) matches any single character in a regular expression. Rather, you want to search for (\.), which will actually match the period. (See here for more details on the period character.)

Finally, if you're trying to match URL's, you could check out this question.

Richard
  • 56,349
  • 34
  • 180
  • 251
0

For words (and I mean words not .com etc) this is simple

You just want to pregmatch

'/\b' . $badword . '\b/'

\b is a word boundary

for full stops you must escape them . to mean them literally (without \ they actually mean and character in a regex) so I would either write a function that looks for full stops and then adds a \ before them or just add them straight into your list with the \ already appended.

GrahamTheDev
  • 22,724
  • 2
  • 32
  • 64