tags:

views:

103

answers:

5

convert this: $300 to this : 300

  • can't do it with intval() or (int) typecasting
  • if the non-numerical character is suffixed (300$), both works and returns 300
  • if it is prefixed it returns 0
  • the non-numerical character can be anything other than the "$"(i.e. "askldjflksdjflsd")

Please help

EDIT : list items are not requirements, they are a list of activities and observations I have made. Sorry:(

+1  A: 
$number = filter_var($number, FILTER_SANITIZE_NUMBER_INT);
Chacha102
I get "Warning: filter_input() expects parameter 1 to be long, string given in php shell code on line 1" in PHP 5.2.10
Matchu
Did you mean `filter_var()`?
Ignacio Vazquez-Abrams
Yeah, parameter 1 should be a constant. Parameter 2 should be the variable. http://php.net/manual/en/function.filter-input.php
Dathan
Went ahead and made the `filter_var` change, since that clearly seems to be the intent.
Matchu
+5  A: 
preg_match('/\d+/', $num, $matches);
echo $matches[0];
Ignacio Vazquez-Abrams
Do remember to make sure that you actually get a match at all, though. You could also try wrapping the expression in a group so you get all groups of digits contained in the string, which may be useful (especially if you need tighter matching, e.g. the number must be prefixed by a specific substring. Also you may need to replace the regex with `"/\d+(\.\d+)?/"` if you need to account for decimals, too (or `"/(\d+|\d*\.\d+)/"` if you want decimals with a notation like `".50"` (=0.5) too.
Alan
+1  A: 
$number = (integer) str_replace('$', '', $number);
Coronatus
Does not match all of the OP's requirements.
Matchu
Yeh it does. He said no use of `(int)`. I used `(integer)`
Coronatus
"the non-numerical character can be anything other than the "$"(i.e. "askldjflksdjflsd")", for example. I think when he said not to use `(int)`, it was because using `(int)` alone doesn't get the job done.
Matchu
Violates two of the bullets in the question: "can't do it with intval() or (int) typecasting" (though that may have been an observation that those don't work on the target strings, not a requirement); "the non-numerical character can be anything other than the '$' (i.e. 'askldjflksdjflsd')"
Dathan
Would revoke downvote, given clarification that apparently the bullets were observations rather than clarifications; however, vote too old to be allowed to change.
Matchu
@matchu Agreed. However, there's an exception for edited questions. Maybe would allow Coronatus to recoup some rep with a little bit of coordination?
Dathan
@Dathan: made a nominal formatting edit to allow vote changes.
Matchu
@Matchu and I've removed the downvote.
Dathan
+3  A: 

You can get rid of all the non-digits in the input by doing:

$input = preg_replace('/\D/','',$input);
codaddict
+2  A: 
print (int) trim('$300', '$');

No need for a regex.

toscho