James Wilson James Wilson - 1 year ago 41
PHP Question

Can a regular expression replace rule being written for these conditions?

I'm trying to submit some information to an API but one of the error messages I get back is:

Field must contain only: upper case letters (A-Z), numbers (0-9), full
stop (.), forward slash (/), dash (-), Ampersand (&) and space

Using regular expression in PHP, can a rule be written that replaces any characters other than the ones specified in the error message?

I suck at regular expression but I bet this is quite easy for someone else! Thank you.

I can obviously set the whole thing to strtoupper() so the first bit I can take care of!

Answer Source

The easiest way would be to use preg_replace.

Example: $str = preg_replace('/[^A-Z\d.\/\-&]+/', '', $str);


  • [^A-Z\d./-&]+ match a single character not present in the list below
    • Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
    • A-Z a single character in the range between A and Z (case sensitive)
    • \d match a digit [0-9]
    • . the literal character .
    • / matches the character / literally
    • - matches the character - literally
    • & a single character in the list & literally (case sensitive)