0

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
  • [^0-9] matches 'not a digit from 0-9'.
    – Mark Byers
    Jul 29, 2010 at 18:40

3 Answers 3

2

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)
4
  • Thanks, but when I apply it it returns nothing: var_dump (preg_replace('/(^-?[0-9]+)?.*|^[^-0-9]+/','$1', '--$ ----matches-- 12--')); //output string '' (length=0)
    – jartaud
    Jul 29, 2010 at 19:14
  • @jartaud: I withdrew my first suggestion.
    – Gumbo
    Jul 29, 2010 at 19:28
  • the panorama is: Im wainting for a negative _GET variable which helps me with the JS go method. Now what I m trying to do is remove all chars except the minus sign ?get=--2'''#$%$%$ should be: ?get=-2
    – jartaud
    Jul 29, 2010 at 19:29
  • @At all, this: $1 is very important
    – jartaud
    Jul 29, 2010 at 19:46
1
/^-\d+$/

or if minus is optional

/^-?\d+$/
1

Should be as simple as...

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

Update

preg_replace('#-\d#', $replacement, $input);
3
  • note the question mark makes the minus sign optional, if it's required just remove the question mark. Jul 29, 2010 at 18:38
  • Thanks for your help, yes the sign is required and I only need one in front (-digit)
    – jartaud
    Jul 29, 2010 at 18:41
  • Thanks again, it keeps returning a lot of "-", I need only one in front the \d
    – jartaud
    Jul 29, 2010 at 19:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.