-1

How to make a preg_match pass when the subject does not contain bad words? This is doing the inverse:

$pattern = '/\b(some|bad|words)\b/i';

function matches($pattern, $value) {
    echo "matches $pattern: $value, matches: " . preg_match($pattern, $value)."\n";
}

matches($pattern, "This should match");
matches($pattern, "This bad string should not match");

All examples I found so far do the opposite: they match when subject contains bad words.

I want it to match when it does not contain bad words.

Tried several combinations and searches, but could not find a solution. Using '?!' with '\b' seems to be not possible?

Kees van Dieren
  • 1,232
  • 11
  • 15
  • 1
    `if(!preg_match(.....))` - simple. – ArtisticPhoenix Dec 24 '18 at 21:54
  • We have a 4GL tool written in PHP that allows specifying a 'validationPattern' attribute, in which we cannot invert the outcome. Thanks anyhow for your suggestion. – Kees van Dieren Dec 24 '18 at 21:58
  • The only reason to use the match function is to actually match something. If you don't want to match some words, well, what words do you want to match ? –  Dec 24 '18 at 23:30

2 Answers2

0
^((?!\b(some|bad|words)\b).)*$
Danon
  • 2,771
  • 27
  • 37
-1

You can use this

^((?!some|bad|words).)*$

Demo

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • Thanks for your reaction. This actually also matches partial words, like someday or badly. This pattern was the solution (based on answer in 'marked as duplicate' question): `/^(?:(?!\b(some|bad|words)\b).)*$/i` – Kees van Dieren Dec 24 '18 at 21:56
  • @KeesvanDieren your regex will match `o'some;` use `space` instead of `\b` – Code Maniac Dec 27 '18 at 18:43