Anam Anam - 10 months ago 70
PHP Question

Becs character set regex

I am working on a project where i have to validate the BECS characters. Bulk Electronic Clearing System (BECS) only allowed the following characters.

BECS Character set

Type Description
Numeric 0 to 9
Alphabetic Uppercase A to Z and Lowercase a to z
+ Plus sign
- Minus sign or hyphen
@ At sign
SP Blank space
$ Dollar sign
! Exclamation mark
% Percentage sign
& Ampersand
( Left Parenthesis
) Right Parenthesis
* Asterik
. Period or decimal point
/ Solidus (slash)
# Number Sign (Pound or Hash)
= Equal Sign
: Colon
; Semicolon
? Question mark
, Comma
’ Apostrophe
[ Left square bracket
] Right square bracket
_ Low line (underscore)
^ Circumflex

I have tried the following but not working:

preg_match("/^[A-Za-z0-9^_[]',?;:=#/.*()&%!$ @+-]+$/", $string);


Inside character classes, you don't need to escape most of the metacharacters.

/^[A-Za-z0-9^_[\]',?;:=#\/.*()&%!$ @+-]+$/
  • ] is escaped to prevent it from closing the character class
  • / needs to be escaped because we're using it as regex delimiter
  • - doesn't need to be escaped because it's the last character in the class
  • ^ doesn't need to be escaped because it's not the first character in the class

Or, if you want a shorter expression, the following regex covers the same range:

/^[ !#-;=?-[\]^_a-z]+$/