Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex allows only 1 character

Tags:

regex

php

$rex = '/^[^<,"@?=>|;#]$/i';

I'm having trouble with this regular expression. The idea is that the input fields are checked for certain characters and if present, throw an error.

This regex is throwing errors for every string longer than 1 character. Can anyone tell me what I'm doing wrong?

EDIT: People are saying they don't see what I want to do with this regex. What I want to do is refuse the input if one of the following characters is part of the entered string:

< > , " @ ? = | ; #

EDIT2: JG's "valid" regex does the trick.

like image 663
KdgDev Avatar asked Feb 23 '26 11:02

KdgDev


1 Answers

You have the $ after your expression and the ^ in the beginning, which means you are accepting exactly one character.

EDIT (based on the comments):

You can try to see if your input fields only have valid characters, by matching it against this (if it matches, it means there are no invalid characters):

$rex = '/^[^<,"@$?=>|;#]+$/i'

You can also do the reverse, that is, test if your input fields have any invalid characters, using the regex provided by chaos:

$rex = '/[<,"@$?=>|;#]/';

This way, if the regex matches, then it means you have invalid characters.

like image 141
João Silva Avatar answered Feb 25 '26 00:02

João Silva