How to match exact word anywhere in string with PHP regexp

后端 未结 4 677
醉梦人生
醉梦人生 2021-01-27 11:15

I want to find out if user has used the words admin or username anywhere in their possible username string.

So if user wants to use admin

相关标签:
4条回答
  • 2021-01-27 11:54

    Just look for words using word boundaries:

    /\b(?:admin|username)\b/i
    

    and if there is a match return error e.g.

    if (preg_match('/\b(?:admin|username)\b/i', $input)) {
        die("Invalid Input");
    }
    
    0 讨论(0)
  • 2021-01-27 11:58

    Square brackets in a regexp are not for grouping, they're for specifying character classes; grouping is done with parentheses. You don't want to anchor the regexp with ^ and $, because that will only match at the beginning and end of the string; you want to use \b to match word boundaries.

    /\b(admin|username)\b/i
    
    0 讨论(0)
  • 2021-01-27 12:08

    Try the below snippet to keep your list of words in Array.

    $input = "im username ";
    $spam_words = array("admin", "username");
    $expression = '/\b(?:' . implode($spam_words, "|") . ')\b/i';
    
    if (preg_match($expression, $input)) {
      die("Username contains invalid value");
    }
    else {
      echo "Congrats! is valid input";
    }
    

    Working Fiddle URL:
    http://sandbox.onlinephpfunctions.com/code/6f8e806683c45249338090b49ae9cd001851af49

    0 讨论(0)
  • 2021-01-27 12:14

    This might be the pattern that you're looking for:

    '#(^|\s){1}('. $needle .')($|\s|,|\.){1}#i'
    

    Some details depend on the restrictions that you want to apply.

    0 讨论(0)
提交回复
热议问题