Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
FILTER_SANITIZE_NUMBER_INT constant in PHP
The FILTER_SANITIZE_NUMBER_INT constant removes all characters except digits, plus and minus signs from a string. It's commonly used to clean user input before processing numeric data.
Syntax
filter_var($value, FILTER_SANITIZE_NUMBER_INT)
Parameters
The filter_var() function with FILTER_SANITIZE_NUMBER_INT accepts −
- $value − The string to be sanitized
- FILTER_SANITIZE_NUMBER_INT − The filter constant that removes illegal characters
Return Value
Returns a string containing only digits (0-9), plus (+), and minus (-) signs. All other characters are removed.
Example
Here's how to sanitize a string containing mixed characters ?
<?php
$var = "4-5+9p";
$sanitized = filter_var($var, FILTER_SANITIZE_NUMBER_INT);
var_dump($sanitized);
// More examples
$examples = ["abc123def", "++--789xyz", "12.34", "1,234"];
foreach ($examples as $example) {
echo "Original: '$example' -> Sanitized: '" .
filter_var($example, FILTER_SANITIZE_NUMBER_INT) . "'<br>";
}
?>
string(5) "4-5+9" Original: 'abc123def' -> Sanitized: '123' Original: '++--789xyz' -> Sanitized: '++--789' Original: '12.34' -> Sanitized: '1234' Original: '1,234' -> Sanitized: '1234'
Key Points
- Removes all characters except digits (0-9), plus (+), and minus (-)
- Decimal points and commas are removed
- Multiple plus/minus signs are preserved
- Does not validate if the result is a valid integer
Conclusion
FILTER_SANITIZE_NUMBER_INT is useful for cleaning numeric input by removing unwanted characters while preserving essential numeric symbols. Remember to validate the sanitized result for proper integer format if needed.
Advertisements
