phpstringvalidationcharacterblacklist

How to validate if a string contains a blacklisted character


I have a string and I need to check it for several characters. I can do that with strpos();. But in this case, I would need to use strpos(); several times. something like this:

$str = 'this is a test';
if(
   strpos($str, "-") === false &&
   strpos($str, "_") === false &&
   strpos($str, "@") === false &&
   strpos($str, "/") === false &&
   strpos($str, "'") === false &&
   strpos($str, "]") === false &&
   strpos($str, "[") === false &&
   strpos($str, "#") === false &&
   strpos($str, "&") === false &&
   strpos($str, "*") === false &&
   strpos($str, "^") === false &&
   strpos($str, "!") === false &&
   strpos($str, "?") === false &&
   strpos($str, "{") === false &&
   strpos($str, "}") === false 
  )
    { do stuff }

Now I want to know, is it possible to use a regex to define my condition summary?


Edit: here is some examples:

$str = 'foo'     ----I want this output---> true
$str = 'foo!'    -------------------------> false
$str = '}foo'    -------------------------> false
$str = 'foo*bar' -------------------------> false

and so on. In other word, I want just text character: abcdefghi...


Solution

  • Use negative lookahead assertion.

    if (preg_match("~^(?!.*?[-_^?}{\]\[/'@*&#])~", $str) ){
    // do stuff
    }
    

    This will do the stuff inside braces only if the string won't contain anyone of the mentioned characters.

    If you want the string to contain only word chars and spaces.

    if (preg_match("~^[\w\h]+$~", $str)){
    // do stuff
    }
    

    or

    AS @Reizer metioned,

    if(preg_match("~^[^_@/'\]\[#&*^!?}{-]*$~", $str)){
    

    Replace the * (present next to the character class) in the above with +, if you don't want to match an empty string.

    For only alphabets and spaces.

    if(preg_match("~^[a-z\h]+$~i", $str) ){