intval() question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
nerru86
Forum Newbie
Posts: 2
Joined: Thu Dec 22, 2011 6:15 am

intval() question

Post 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!
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: intval() question

Post by Celauran »

I think preg_replace() is what you're looking for.
User avatar
egg82
Forum Contributor
Posts: 156
Joined: Sat Oct 01, 2011 9:29 pm
Location: Colorado, USA

Re: intval() question

Post by egg82 »

Code: Select all

$new_string = preg_replace("/[^0-9]/", "", $string);
That should help
nerru86
Forum Newbie
Posts: 2
Joined: Thu Dec 22, 2011 6:15 am

Re: intval() question

Post by nerru86 »

Yes, that's what I was looking for, thanks!
Post Reply