Phil Phil - 1 year ago 163
PHP Question

RegEx to match anything BUT decimal numbers with percent symbol

I'm terrible at RegEx. Can anyone show a regex to use if I want to check a string for anything BUT digits 0-9, decimal point and percent sign?

I've tried this...

if (preg_match('/[^0-9.]+%/i', $string)) {
echo 'invalid';

but it's not working correctly. I have a input field which asks a user what the tax rate should be, and this is going to verify they have entered a VALID tax rate. I want them to enter it like "5.2%" rather than in decimal, and I will do the math on the back-end.

A VALID match would be "6%" or "5.2%" etc.
A INVALID match would be "2" or "0.05" or "A"

Answer Source

Look for a valid match, then invert it in the test:

if (!preg_match('/[\d.]%/', $string) {
    echo 'invalid';

But since this is supposed to test the whole string, not just look for a percentage anywhere in it, you need to anchor it:

if (!preg_match('/^[\d.]+%$/', $string) {
    echo 'invalid';

Note that this will allow something like .%. You probably should use something like Regular expression to match numbers with or without commas and decimals in text to match the number part.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download