Help with applying exception in preg_replace

2019-09-07 00:34发布

问题:

Hello How can I can I allow only digit [^0-9] and a minus sign in front the digit. Example : Valid = -1...-9, Invalid = --1-...

回答1:

Just remove every invalid character and check if the remaining has a valid format:

$cleaned = preg_replace('/[^-0-9]+/', '', $str);
if (preg_match('/^-?[0-9]+$/', $cleaned)) {
    // now valid
}

Ok, here’s another suggestion:

preg_replace('/.*?(-?\d+).*/', '$1', $str)


回答2:

/^-\d+$/

or if minus is optional

/^-?\d+$/


回答3:

Should be as simple as...

preg_match('#^-?[0-9]$#', $input);

Update

preg_replace('#-\d#', $replacement, $input);