Chat LIVE With Programming Experts! There Are 23 Online Right Now...

Welcome to Dream.In.Code
Become a PHP Expert!

Join 244,308 PHP Programmers for FREE! Get instant access to thousands of PHP experts, tutorials, code snippets, and more! There are 807 people online right now. Registration is fast and FREE... Join Now!




How do I allow only numbers in a text field?

2 Pages V  1 2 >  
Reply to this topicStart new topic

How do I allow only numbers in a text field?, DoI use ereg?

alyis
30 Sep, 2008 - 07:08 PM
Post #1

New D.I.C Head
*

Joined: 12 Mar, 2008
Posts: 19


My Contributions
I need to allow users to only be able to submit numbers into a text field and if they submit anything else it needs to strip all other characters be it letters or symbols. If someone could help me with this it would be very much apprecaited...because as of right now a user can enter + signs on both side of a number like so, +10000+, and it will submit it and send that amount of money even if the user does not have that much.


CODE
<?php
include 'header.php';

if($_POST['sendmoney'] != ""){
  $money_person = new User($_POST['theirid']);

  if($user_class->money >= $_POST['amount'] && $_POST['amount'] > 0 && $user_class->id != $money_person->id){
    $newmoney = $user_class->money - $_POST['amount'];
    $result = mysql_query("UPDATE `grpgusers` SET `money` = '".$newmoney."' WHERE `id`='".$_SESSION['id']."'");

    $newmoney = $money_person->money + $_POST['amount'];
    $result = mysql_query("UPDATE `grpgusers` SET `money` = '".$newmoney."' WHERE `id`='".$_POST['theirid']."'");
    echo "You have successfully transferred $".$_POST['amount']." to ".$money_person->formattedname.".";
    Send_Event($user_points->id, "You have been sent $".$_POST['amount']." from ".$user_class->formattedname);
  } else {
    echo "You don't have enough money to do that!";
  }
}
?>

<div class="content"><u>Send Money</u><br>
<form name='login' method='post' action='sendmoney.php'>
  <p>&nbsp;</p>
  <table border='0' cellpadding='0' cellspacing='0'>
    <tr>
      <td width='35%' height='27'>Amount Of Money</td>
      <td width='65%'>
        <input name='amount' type='text' size='22'>
        </td>
    </tr>
        <tr>
      <td width='35%' height='27'>User ID</td>
      <td width='65%'>
        <input name='theirid' type='text' size='22' value='<? echo $_GET['person'] ?>'>
        </td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td>
        <input type='submit' name='sendmoney' value='Send Money'>
        </td>
    </tr>
  </table>
</form>
</div>


<?php
include 'footer.php';
?>


User is offlineProfile CardPM
+Quote Post


grimpirate
RE: How Do I Allow Only Numbers In A Text Field?
30 Sep, 2008 - 08:46 PM
Post #2

D.I.C Regular
Group Icon

Joined: 3 Aug, 2006
Posts: 344



Thanked: 12 times
Dream Kudos: 375
My Contributions
CODE
$length = strlen($_POST['amount']);
for($i = 0; $i < $length; $i++){
$numbers = '';
$temp = ord(substr($_POST['amount'], $i, 1));
if($temp > 47 && $temp < 58)
$numbers .= chr($temp);
}
if(strlen($numbers) == 0) $numbers = 0;


This post has been edited by grimpirate: 30 Sep, 2008 - 08:47 PM
User is offlineProfile CardPM
+Quote Post

alyis
RE: How Do I Allow Only Numbers In A Text Field?
1 Oct, 2008 - 03:34 AM
Post #3

New D.I.C Head
*

Joined: 12 Mar, 2008
Posts: 19


My Contributions
Could you please explain your as to help me learn what I need to do....
User is offlineProfile CardPM
+Quote Post

pemcconnell
RE: How Do I Allow Only Numbers In A Text Field?
1 Oct, 2008 - 03:46 AM
Post #4

D.I.C Regular
Group Icon

Joined: 5 Aug, 2008
Posts: 467



Thanked: 49 times
Dream Kudos: 75
My Contributions
*EDIT*

I would change the second and third lines from this:

CODE

for($i = 0; $i < $length; $i++){
$numbers = '';


to this:

CODE

$numbers = '';
for($i = 0; $i < $length; $i++){


As $numbers was being reset to '' in every instance of the loop.

*END EDIT*

To explain what grim's code does, it loops through the amount entered, checking each number / letter.

$temp is the ASCII value of the individual character of each number/letter in amount. e.g.

4734556
$temp on the first loop is the ASCII value of 4, 7 on the second loop, 3 on the third loop, 4 on the 4th etc.

So, if $temp is between 48 and 57, it is concidered a number (I'm assuming that 48 - 57 is the ASCII range of 0 - 9, don't know the ASCII values of the top of my head)

If it is in this range then it is a number, so it is appended to the variable $numbers.

So, if you where to enter this as the amount:

54asd65asd45

You would get 546545 as the $numbers value.

All in all a nice function that i think I'll be adding to my library, thanks grim smile.gif

This post has been edited by pemcconnell: 1 Oct, 2008 - 04:52 AM
User is offlineProfile CardPM
+Quote Post

alyis
RE: How Do I Allow Only Numbers In A Text Field?
1 Oct, 2008 - 03:52 AM
Post #5

New D.I.C Head
*

Joined: 12 Mar, 2008
Posts: 19


My Contributions
Thankyou pem and grim. This helps me alot with my game. IF anyone else has any other ways of doing this feel free to share them.

This post has been edited by alyis: 1 Oct, 2008 - 03:53 AM
User is offlineProfile CardPM
+Quote Post

pemcconnell
RE: How Do I Allow Only Numbers In A Text Field?
1 Oct, 2008 - 04:55 AM
Post #6

D.I.C Regular
Group Icon

Joined: 5 Aug, 2008
Posts: 467



Thanked: 49 times
Dream Kudos: 75
My Contributions
I added grims code into a function with the tiny change i mentioned in my last post:

CODE

function getNumbersOnly($value){
    $numbers = '';
    for($i = 0; $i < strlen($value); $i++){
        $temp = ord(substr($value, $i, 1));
        if($temp > 47 && $temp < 58){
            $numbers .= chr($temp);
        }
    }
    return $numbers;
}


Full credit to grimpirate for the function.

This post has been edited by pemcconnell: 1 Oct, 2008 - 05:22 AM
User is offlineProfile CardPM
+Quote Post

alyis
RE: How Do I Allow Only Numbers In A Text Field?
1 Oct, 2008 - 05:15 AM
Post #7

New D.I.C Head
*

Joined: 12 Mar, 2008
Posts: 19


My Contributions
I am not quite sure how i should be implementing this into my code..I am very new to PHP. Can I also see an example of how I would only allow numbers using ereg() statements? And also how to replace anything eneteredinto the field such as +123123+ to remove the + and + fromt he outsides and only keep the 123123?
User is offlineProfile CardPM
+Quote Post

pemcconnell
RE: How Do I Allow Only Numbers In A Text Field?
1 Oct, 2008 - 05:28 AM
Post #8

D.I.C Regular
Group Icon

Joined: 5 Aug, 2008
Posts: 467



Thanked: 49 times
Dream Kudos: 75
My Contributions
Here is an example of the code:

CODE

function getNumbersOnly($value){
    $numbers = '';
    for($i = 0; $i < strlen($value); $i++){
        $temp = ord(substr($value, $i, 1));
        if($temp > 47 && $temp < 58){
            $numbers .= chr($temp);
        }
    }
    return $numbers;
}

$amount = getNumbersOnly($_POST['amount']);

?>


So if the user has entered +123456+ into the 'amount' field and posted the form, this line:

CODE

$amount = getNumbersOnly($_POST['amount']);


would strip any non-numbers from the data, meaning the code would read:

CODE

$amount = 123456;


*Again, all credit should go to grim for that

To use regular expressions to validate if a character is in the string, you could use:

CODE

$text = "mixedcharacters012345&../@";



if (ereg('[^A-Za-z0-9]', $text)) {

  echo "This contains characters other than just numbers";

}

else {

  echo "This contains only numbers";    

}


Taken from this site
User is offlineProfile CardPM
+Quote Post

akozlik
RE: How Do I Allow Only Numbers In A Text Field?
1 Oct, 2008 - 05:29 AM
Post #9

D.I.C Addict
Group Icon

Joined: 25 Feb, 2008
Posts: 770



Thanked: 36 times
Dream Kudos: 800
My Contributions
Here's some Javascript that you can include for your form:

How Can I Use Javascript to Allow Only Numbers to be Entered in a Textbox?

Wow, that's a long title.

You could use that on the front end of the site, to limit what can be entered into the form. Then after the form is submitted you could use PHP to double check that the string only contains numbers using any of the methods that have been given to you.

It's very important to double check with PHP, as Javascript can easily be beat.

Good luck!
User is offlineProfile CardPM
+Quote Post

CTphpnwb
RE: How Do I Allow Only Numbers In A Text Field?
1 Oct, 2008 - 05:35 AM
Post #10

D.I.C Lover
Group Icon

Joined: 8 Aug, 2008
Posts: 1,571



Thanked: 94 times
Dream Kudos: 100
Expert In: PHP

My Contributions
QUOTE(grimpirate @ 30 Sep, 2008 - 09:46 PM) *

CODE
$length = strlen($_POST['amount']);
for($i = 0; $i < $length; $i++){
$numbers = '';
$temp = ord(substr($_POST['amount'], $i, 1));
if($temp > 47 && $temp < 58)
$numbers .= chr($temp);
}
if(strlen($numbers) == 0) $numbers = 0;



I would add a test at the end to see if $numbers == $_POST['amount']. That's because if somebody enters something like "99 Main Street", this will result in $numbers = 99. It's likely that the user in such a case will have typed the information in the wrong field, and the intended number for this field is either missing completely or entered elsewhere.

If you confirm that $numbers == $_POST['amount'] then at least you know that they meant to enter a number.
User is online!Profile CardPM
+Quote Post

akozlik
RE: How Do I Allow Only Numbers In A Text Field?
1 Oct, 2008 - 05:39 AM
Post #11

D.I.C Addict
Group Icon

Joined: 25 Feb, 2008
Posts: 770



Thanked: 36 times
Dream Kudos: 800
My Contributions
Has everybody forgotten about the built in function is_numeric()?

php

<?php
$number = $_POST['amount'];
$length = strlen($number);
for ($i=0; $i<$length; $i++)
{
if ( !is_numeric($number[$i]) ) $number[$i] = '';
}
?>


Seems a bit simpler. If you can avoid regular expressions, you should.

This actually brings up a good point. When looking to complete a specific tasks, check the documentation on php.net and see if there's a prebuilt function. Often, there are already solutions for what you're trying to find.

Here's where the function description is. Check the left side column for a list of other is_* functions.

Hope that helps.

This post has been edited by akozlik: 1 Oct, 2008 - 05:42 AM
User is offlineProfile CardPM
+Quote Post

alyis
RE: How Do I Allow Only Numbers In A Text Field?
1 Oct, 2008 - 05:46 AM
Post #12

New D.I.C Head
*

Joined: 12 Mar, 2008
Posts: 19


My Contributions
Thank you very much penn for that explantion. It helped me alot I will try to use that right now and tell you how it works for me. Thankyou everyone else as well for the help with this bug.
User is offlineProfile CardPM
+Quote Post

akozlik
RE: How Do I Allow Only Numbers In A Text Field?
1 Oct, 2008 - 06:01 AM
Post #13

D.I.C Addict
Group Icon

Joined: 25 Feb, 2008
Posts: 770



Thanked: 36 times
Dream Kudos: 800
My Contributions
One last example if you wanted to use regex. You can use the preg_replace() function to replace the characters, without the need to loop through each one. I actually kinda dig this one because it's only three lines.

php

$number = $_POST['amount'];
$pattern = '/[^0-9]/'; // This means to search for anything that is not a number
$string = preg_replace($pattern, '', $number); // Replaces anything that matches the pattern with an empty string

// String has now been stripped of all non numeric characters


Finally, you could use this all in a function like so:

php

function strip_to_numbers_only($string)
{
$pattern = '/[^0-9]/';
return preg_replace($pattern, '', $string);
}

// Call the function like this
$string = '9034klfa9032jklfau2hhf234';
$string = strip_to_numbers_only($string);


Hope you can add that to your functions library. I'm gonna go submit it to the code snippets now.

Adios

*EDIT*
I made a mistake and had preg_replace($pattern, '', $string). Should be preg_replace($pattern, '', $number) if used with the first code sample. The second sample is correct.
*END EDIT*

This post has been edited by akozlik: 1 Oct, 2008 - 06:37 AM
User is offlineProfile CardPM
+Quote Post

alyis
RE: How Do I Allow Only Numbers In A Text Field?
1 Oct, 2008 - 06:41 AM
Post #14

New D.I.C Head
*

Joined: 12 Mar, 2008
Posts: 19


My Contributions
CODE
<?php
include 'header.php';

if($_POST['sendmoney'] != ""){
  $money_person = new User($_POST['theirid']);
  
   if($user_class->money >= $_POST['amount'] && $_POST['amount'] > 0 && $user_class->id != $money_person->id){
    
    function strip_to_numbers_only($string)  
    {  
         $pattern = '/[^0-9]/';  
         return preg_replace($pattern, '', $string);  
    }
  
    $newmoney = strip_to_numbers_only($user_class->money - $_POST['amount']);
    $result = mysql_query("UPDATE `grpgusers` SET `money` = '".$newmoney."' WHERE `id`='".$_SESSION['id']."'");

    $newmoney = strip_to_numbers_only($money_person->money + $_POST['amount']);
    $result = mysql_query("UPDATE `grpgusers` SET `money` = '".$newmoney."' WHERE `id`='".$_POST['theirid']."'");
    echo "You have successfully transferred $".$_POST['amount']." to ".$money_person->formattedname.".";
    Send_Event($user_points->id, "You have been sent $".$_POST['amount']." from ".$user_class->formattedname);
  } else {
    echo "You don't have enough money to do that!";
  }
}
?>



I have fixed the problem where it puts you in the negatives... but you are still able to send using the +100+ and all it does is do the absolute value of how much you would be in the negatives..
User is offlineProfile CardPM
+Quote Post

akozlik
RE: How Do I Allow Only Numbers In A Text Field?
1 Oct, 2008 - 06:55 AM
Post #15

D.I.C Addict
Group Icon

Joined: 25 Feb, 2008
Posts: 770



Thanked: 36 times
Dream Kudos: 800
My Contributions
I'm sorry, I didn't quite understand that. Was there another problem popping up?
User is offlineProfile CardPM
+Quote Post

grimpirate
RE: How Do I Allow Only Numbers In A Text Field?
1 Oct, 2008 - 10:30 AM
Post #16

D.I.C Regular
Group Icon

Joined: 3 Aug, 2006
Posts: 344



Thanked: 12 times
Dream Kudos: 375
My Contributions
@pem: thx for the revision lol I can't believe I made that mistake, then again I was pretty sleepy.

@akozlik: I did indeed forget about the is_numeric function. In regards to the regex I usually avoid using them if I can come up with a way to do it using simple string operations. I would imagine those are faster than regex, but testing it would be the only way to be sure.
User is offlineProfile CardPM
+Quote Post

akozlik
RE: How Do I Allow Only Numbers In A Text Field?
1 Oct, 2008 - 11:00 AM
Post #17

D.I.C Addict
Group Icon

Joined: 25 Feb, 2008
Posts: 770



Thanked: 36 times
Dream Kudos: 800
My Contributions
Yeah I totally understand that regex is not the way to go. Initially I thought so too with this problem. However, the regex method is much more efficient. It simply runs the preg_replace() function once to replace all the non-numeric characters.

The loop method requires that the ord() function, substr() function and chr() functions all be run $length number of times. If you have a string of 10 characters and you want to replace all non-numeric characters using the loop method, each one of those functions would be executed 10 times. That totals out to 30 function calls by the time the loop's over!

It took a minute to find the preg_replace() function, but in this situation it's definitely the more efficient way to go.
User is offlineProfile CardPM
+Quote Post

akozlik
RE: How Do I Allow Only Numbers In A Text Field?
1 Oct, 2008 - 11:25 AM
Post #18

D.I.C Addict
Group Icon

Joined: 25 Feb, 2008
Posts: 770



Thanked: 36 times
Dream Kudos: 800
My Contributions
@grimpirate and anyone else who's interested:

What you said made me think, so I went ahead and did some quick benchmarking. All credit for the microtime_float() function goes to This Article

I ran the following code, benchmarking both functions and sending out their results to the screen.

php

<?php

function strip_non_numeric($string)
{
$pattern = '/[^0-9]/';
return preg_replace($pattern, '', $string);
}

function loop_non_numeric($string)
{
$numbers = '';
for($i = 0; $i < strlen($string); $i++){
$temp = ord(substr($string, $i, 1));
if($temp > 47 && $temp < 58){
$numbers .= chr($temp);
}
}
return $numbers;
}

function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}

function benchmark($string)
{
echo "String length: " . strlen($string) . "<br />";
$start = microtime_float();
for ($i=0; $i<100000; $i++)
{
$temp = strip_non_numeric($string);
}
$end = microtime_float();
echo "Strip took: " . ($end-$start) . " Seconds<br />";

$start = microtime_float();
for ($i=0; $i<100000; $i++)
{
$temp = loop_non_numeric($string);
}
$end = microtime_float();
echo "Loop took: " . ($end-$start) . " Seconds<br /><br />";
}

$string = '123k';
benchmark($string);

$string = '348jfakl324928249majsf;l24;lkja8902340$%df@#';
benchmark($string);

$string = '348jfakl324928249majsf;l24;lkja8902340$%df@#348jfakl324928249majsf;l24;lkja8902340$%df@#';
benchmark($string);

?>



The results were as follows:
QUOTE

String length: 4
Strip took: 0.52696514129639 Seconds
Loop took: 1.1218490600586 Seconds

String length: 44
Strip took: 1.0355489253998 Seconds
Loop took: 6.1059668064117 Seconds


String length: 88
Strip took: 1.627063035965 Seconds
Loop took: 11.946272134781 Seconds


As you can see, for smaller strings the amount of difference isn't too bad. The preg_replace() method was only about twice as fast as the loop method. However, as the string lengths got greater, the amount of difference could really be seen. The preg_replace method took 1.6 seconds to strip an 88 character string. The loop method took 11.9!

That's the point I was making. All those functions within the loop are executed once per iteration. Doing preg_replace() takes care of it all at once.

Finally, I'm not posting this as a 'my code is better than your code' sort of thing. You had mentioned benchmarking and I had some spare time.

Take care!

This post has been edited by akozlik: 1 Oct, 2008 - 12:25 PM
User is offlineProfile CardPM
+Quote Post

akozlik
RE: How Do I Allow Only Numbers In A Text Field?
1 Oct, 2008 - 11:54 AM
Post #19

D.I.C Addict
Group Icon

Joined: 25 Feb, 2008
Posts: 770



Thanked: 36 times
Dream Kudos: 800
My Contributions
*EDIT*
I removed this previous post because I was full of crap and wrote my benchmarking wrong. I retested and the regex was way faster. Stick with that

This post has been edited by akozlik: 1 Oct, 2008 - 12:19 PM
User is offlineProfile CardPM
+Quote Post

alyis
RE: How Do I Allow Only Numbers In A Text Field?
1 Oct, 2008 - 12:48 PM
Post #20

New D.I.C Head
*

Joined: 12 Mar, 2008
Posts: 19


My Contributions
@akoz right now it if a user has $100 they can enter +1000+ into the sendmoney field. it will send $1000 to the user your sending to and then subtract $1000 from you leaving you with -$900. it needs to strip everything except the numbers so that if you dont have the correct amount of money than it should say "not enough money" which it does if you dont use the +'s
User is offlineProfile CardPM
+Quote Post

2 Pages V  1 2 >
Fast ReplyReply to this topicStart new topic

Time is now: 7/4/09 06:57PM

Live PHP Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

PHP Tutorials

Reference Sheets

PHP Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month