|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2011-12-16 00:07 UTC] klaussilveira@php.net
Description:
------------
The filter_var FILTER_SANITIZE_NUMBER_INT filter fails to sanitize plus and minus
signs in a string. This is the expected behavior, since + and - are accepted in
an integer. However, the filter fails to recognize multiple + and -, returning an
string instead of an integer.
For example:
filter_var("I'm+captain4", FILTER_SANITIZE_NUMBER_INT; // returns +4, OK!
filter_var("I'm++captain4", FILTER_SANITIZE_NUMBER_INT; // returns ++4, FAILURE!
I wrote a small patch that makes the filter ignore + and - signs, which, i
believe, it's the best behavior for this.
Test script:
---------------
<?php
// Normal behavior
$a = filter_var("I'm+captainSp4rrow!", FILTER_SANITIZE_NUMBER_INT);
$b = filter_var("I'm+captain4", FILTER_SANITIZE_NUMBER_INT);
echo "$a and $b" . PHP_EOL;
echo $a + $b . PHP_EOL;
// Problems comes in when we have multiple minus or plus signs in the string
$a = filter_var("I'm++captainSp4rrow!", FILTER_SANITIZE_NUMBER_INT);
$b = filter_var("I'm++captain4", FILTER_SANITIZE_NUMBER_INT);
echo "$a and $b" . PHP_EOL;
echo $a + $b . PHP_EOL;
Expected result:
----------------
4 and 4
8
4 and 4
8
Patchessanitize_integers (last revision 2011-12-16 00:07 UTC by klaussilveira@php.net)Pull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sat Nov 01 23:00:01 2025 UTC |
The most elegant solution was to detect only + and - signs that are next to a number, and remove all others. For example: filter_var("ad--td#$@++qsdh-3", FILTER_SANITIZE_NUMBER_INT); // returns -3 Right now, the filter behavior is: filter_var("ad--td#$@++qsdh-3", FILTER_SANITIZE_NUMBER_INT); // returns --++-3 Which is VERY bad and HORRIBLY wrong.Plus, this matches perfectly the documentation ("Remove all characters except digits, plus and minus sign.")