views:

75

answers:

3

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  A: 

Should be as simple as...

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

Update

preg_replace('#-\d#', $replacement, $input);
Cags
note the question mark makes the minus sign optional, if it's required just remove the question mark.
Cags
Thanks for your help, yes the sign is required and I only need one in front (-digit)
jartaud
I added an update based on new information.
Cags
Thanks again, it keeps returning a lot of "-", I need only one in front the \d
jartaud
+2  A: 
/^-\d+$/

or if minus is optional

/^-?\d+$/
M42
+2  A: 

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)
Gumbo
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
@jartaud: I withdrew my first suggestion.
Gumbo
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
@Gumbo Thanks it works, your help is really appreciate, thanks again
jartaud
@At all, this: $1 is very important
jartaud