Regex allows only 1 character

后端 未结 6 1441
长情又很酷
长情又很酷 2021-01-22 03:50
$rex = \'/^[^<,\"@?=>|;#]$/i\';

I\'m having trouble with this regular expression. The idea is that the input fields are checked for certain chara

6条回答
  •  太阳男子
    2021-01-22 04:09

    You'll want '/^[^<,"@$?=>|;#]+$/i' or '/^[^<,"@$?=>|;#]*$/i'.

    For an example:

    $valid = 'Hello';
    $invalid = 'h

    Which outputs:

    'Hello' gives 1
    'h

    What I simply did was take your expression and add a + or * after your character group.

    In regular expressions, * means match 0 or more occurences, and + means match 1 or more.

    Since ^ means the beginning of the string and $ the end, without a + or *, you tell it to match a string the consists of exactly one occurrence of a non-special character, thus why it errors if your string is longer than one character.

    If you wish, you can also remove the i at the end of the expression, as you don't need to do a case-insensitive match when no letters are involved in your expression.

    For more information on regular expressions, take a look at Regular-Expressions.info.

提交回复
热议问题