How to create validation with special characters

Asked

Viewed 1,528 times

2

I would like to know how to create a validation with preg_macth() where you have to accept these characters from the keyboard:

/^([a-zA-Z0-9]{6,40})$/


`~!@#$%^&*()_-+={}[]\|:;"'<>,.?/

Except the spaces.

2 answers

2


You need to include these characters in the list of what is accepted (the part between [ and ]). As in your list some characters have special meaning in regular expressions, it is necessary to escape them with \:

^([`~!@#$%^&*()_\-+={}[\]\\\|:;"'<>,\.\?\/a-zA-Z0-9]{6,40})$

See a functional example

  • I was testing on this site: https://pt.functions-online.com/preg_match.html, then put backslash on the characters and it doesn’t work. Error of the site itself. I went on the site you passed, perfect. ATT

0

From the analysis I made of your need, using the ascii table, and the attack command for hexadecimal \x## you can reduce your regex to simply :

^([\x21-\x7E]{6,40})$

That will encompass all your characters.

see :

!	21
"	22
#	23
$	24
%	25
&	26
'	27
(	28
)	29
*	2A
+	2B
,	2C
-	2D
.	2E
/	2F
0-9	30 a 39
:	3A
;	3B
<	3C
=	3D
>	3E
?	3F
@	40
A-Z	41 a 5A
[	5B
\	5C
]	5D
^	5E
_	5F
`	60
a-z	61 a 7A
{	7B
|	7C
}	7D
~	7E

Browser other questions tagged

You are not signed in. Login or sign up in order to post.