RE: [PHP] Validating get and post data
| From: | Ford, Mike [LSS] | Date: | Tue, 03 Dec 2002 11:24:09 +0000 |
| Subject: | RE: [PHP] Validating get and post data | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-126833@lists.php.net to get a copy of this message | ||
> -----Original Message-----
> From: Beth Gore [mailto:bethgore@tesco.net]
> Sent: 03 December 2002 02:12
>
> However bizarrely this seems to behave incorrectly, as it
> cuts out "0"
> as well. Can anyone explain why it does this?
>
> function stripnum($rawinput)
> {
>
> for($x=0;$x < strlen($rawinput);$x++)
> {
> $c = substr($rawinput,$x,1);
>
> switch($c){
>
> case ($c > chr(47) and $c < chr(58)):
> $output .=$c;
> break;
>
> default:
> echo "escaped character at ".$x;
> break;
> }
>
> }
>
> return $output;
> }
>
>
> I just can't find the bug in my code at all,
Well, that's just not the way the switch statement works! The value of the
expression after each case is compared for equality to the expression after
switch -- so, in this case, you have the equivalent of:
if ($c == ($c > chr(47) and $c < chr(58)))
and I think you can figure out why that gives the wrong answer!
In fact, switch doesn't work well for this kind of test, as you'd have to
write it as:
switch ($c):
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
$output .= $c;
break;
default:
echo "escaped character at ".$x;
break;
endswitch;
You're much better off here with a straight if/else.
Cheers!
Mike
---------------------------------------------------------------------
Mike Ford, Electronic Information Services Adviser,
Learning Support Services, Learning & Information Services,
JG125, James Graham Building, Leeds Metropolitan University,
Beckett Park, LEEDS, LS6 3QS, United Kingdom
Email: m.ford@lmu.ac.uk
Tel: +44 113 283 2600 extn 4730 Fax: +44 113 283 3211