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
2010-07-29 18:38:10
note the question mark makes the minus sign optional, if it's required just remove the question mark.
Cags
2010-07-29 18:38:51
Thanks for your help, yes the sign is required and I only need one in front (-digit)
jartaud
2010-07-29 18:41:43
I added an update based on new information.
Cags
2010-07-29 18:58:33
Thanks again, it keeps returning a lot of "-", I need only one in front the \d
jartaud
2010-07-29 19:17:07
+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
2010-07-29 19:02:59
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
2010-07-29 19:14:23
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
2010-07-29 19:29:07