PHP: only alphanumeric and other special characters

I want to use a regex to limit valid characters. I.e:

a - z /* a to z */ A - Z /* A to Z */ 0 - 9 /* 0 to 9 */ _ - /* underscore & dash */ ~ ! @ # $% ^ & * () /* allowed special characters */ 

and this is my regular function:

 function validChr($str) { return preg_match('/^[A-Za-z0-9_~\ -!@ #\$%\^&*\(\)]+$/',$str); } 

I really tried this and the result is how I want, but I was still not sure. Is my regex correct? Or are there other forms of regex? Please help as I am still new to this regex. Thanks.

+6
source share
1 answer

It works as it should.

You must add \ before * to avoid it.

Take a look here: Regular Expression Test

+8
source

All Articles