Page 1 of 1

intval() question

Posted: Thu Dec 22, 2011 6:41 am
by nerru86
Hello,

Basically what I'm trying to do is validate a numeric input. This will be used in a function to validate d.o.b from the form later. To shield the application from arbitrary input I need to make sure the number supplied in dob is actually a number (Problem is, I want to allow both . and / dividers for the date so that both 01.01.2011 and 01/01/2011 are both valid). I read about intval() which, as far as I understand, is supposed to return the numeric value of the string (that is only numbers but not letters or symbols). So the following is just a function which is supposed to perform the task:

Code: Select all

function numericFilter($input){
	return intval($input);
}
And this is the test code:

Code: Select all

<?php
$testString = "12rrr44";
$testString2 = "a12rrr44";
echo numericFilter($testString)."<br>";
echo numericFilter($testString2)."<br>";
?>
And finally the output:
Test

12
0

which is not what I want. I'm starting to think I misinterpreted the intval() function. Is there another function that removes all non numeric characters from the string or is that something I have to write myself, or something I have done wrong with intval? It's not hard to write a string numeric filter but as far as I know most of the standard functions are in C, which is faster than a function in php.

Thanks in advance!

Re: intval() question

Posted: Thu Dec 22, 2011 10:00 am
by Celauran
I think preg_replace() is what you're looking for.

Re: intval() question

Posted: Thu Dec 22, 2011 11:11 am
by egg82

Code: Select all

$new_string = preg_replace("/[^0-9]/", "", $string);
That should help

Re: intval() question

Posted: Fri Dec 23, 2011 3:05 am
by nerru86
Yes, that's what I was looking for, thanks!