search

PHP过滤器包含两种类型
Validation:用来验证验证项是否合法
Sanitization:用来格式化被验证的项目,因此它可能会修改验证项的值,将不合法的字符删除等。


input_filters_list()函数用来列出当前系统所支持的所有过滤器。

1 <table>2 <tr><td>Filter Name</td><td>Filter ID</td></tr>3 <?php4 foreach(filter_list() as $id =>$filter)5 {6     echo '<tr><td>'.$filter.'</td><td>'.filter_id($filter).'</td></tr>'."\n";7 }8 ?>9 </table>

以上代码会输出如下信息
Filter Name Filter ID
int 257
boolean 258
float 259
validate_regexp 272
validate_url 273
validate_email 274
validate_ip 275
string 513
stripped 513
encoded 514
special_chars 515
unsafe_raw 516
email 517
url 518
number_int 519
number_float 520
magic_quotes 521
callback 1024
每个过滤器都会拥有一个独自的ID。这里的每个过滤器都能够被filter_var()函数使用。下面将会逐个介绍其使用方法。注意 ,上面的string和strippedID相同,这是因为他们是同一个过滤器,或者说是同一个过滤器的两个别名罢了。
过滤数据
使用filter_var()方法对数据进行过滤,下面是一个简单的过滤例子

1 <?php2 3 /*** an integer to check ***/4 $int = 1234;5 /*** validate the integer ***/6 echo filter_var($int, FILTER_VALIDATE_INT);7 //12348 ?>

 

上面代码将会数据一个整数型的1234,因为$int变量通过的整数类型的验证,这次更换一下$int变量的内容

1 <?php2 3 /*** an integer to check ***/4 $int = 'abc1234';5 /*** validate the integer ***/6 echo filter_var($int, FILTER_VALIDATE_INT);7 8 ?>

 

此时在运行代码,发现没有任何变量输出,这是因为$in变量没有通过验证,因此这个方法返回bool(false)。同时也需要注意 一下,即使$int='',也会返回bool(false)

整数验证
上面的几段代码简单的验证了一个给定值是否为整数的例子。其实FILTER_VALIDATE_INT也提供了数值范围的验证,下面我们 来验证一个变量,判断它是否为整数型,并验证它的值是否在50到100之间

 1 <?php 2 /*** an integer to check ***/ 3 $int = 42; 4 /*** lower limit of the int ***/ 5 $min = 50; 6 /*** upper limit of the int ***/ 7 $max = 100; 8  9 /*** validate the integer ***/10 echo filter_var($int, FILTER_VALIDATE_INT, array("min_range"=>$min, "max_range"=>$max));11 //4212 ?>

 

运行上面的代码,发现42被输出来了,并没有发现任何错误,这是为什么啊?原来想要向验证中添加附加验证规则时候,需要传递一个含有'options'键的数组,向下面这样:

 1 <?php 2 /*** an integer to check ***/ 3 $int = 42; 4 /*** lower limit of the int ***/ 5 $min = 50; 6 /*** upper limit of the int ***/ 7 $max = 100; 8  9 /*** validate the integer ***/10 echo filter_var($int, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$min, "max_range"=>$max)));11 12 ?>

 

运行上面的代码,页面不会有任何输出,因为上面返回了false,说明验证成功。使用该方法也可以对负数进行范围验证同时这种方式也支持单范围取值,即只是指定一个最大值或者最小值的范围,如

<?php/*** an integer to check ***/$int = 12;/*** lower limit of the int ***/$min = 10;/*** validate the integer ***/echo filter_var($int, FILTER_VALIDATE_INT,array('options'=>array('min_range'=>$min)));//12?>

 

上述代码会验证$int是否是大于(不包括等于)$min的整数类型的值,运行代码,输出12
上面的这些例子只是简单的对单个值进行验证,那么如果对一组变量进行验证呢?答案是使用filter_var_array()。该函数可以同时验证多个不同类型的数据。这里先做一个简单的例子

 1 <?php 2  3 /*** an array of values to filter ***/ 4 $arr = array(10,"109","", "-1234", "some text", "asdf234asdfgs", array()); 5  6 /*** create an array of filtered values ***/ 7 $filtered_array = filter_var_array($arr, FILTER_VALIDATE_INT); 8  9 /*** print out the results ***/10 foreach($filtered_array as $key=>$value)11 {12     echo $key.' -- '.$value.'<br />';13 }14 ?>

 

运行上述代码,输出如下
0 -- 10
1 -- 109
2 --
3 -- -1234
4 --
5 --
6 -- Array
FILTER_VALIDATE_INT过滤器同时支持八进制和十六进制,这两种flags是
FILTER_FLAG_ALLOW_HEX
FILTER_FLAG_ALLOW_OCTAL
利用数组传递flags

1 <?php2 3 /*** a hex value to check ***/4 $hex = "0xff";5 6 /*** filter with HEX flag ***/7 echo filter_var($hex, FILTER_VALIDATE_INT, array("flags"=>FILTER_FLAG_ALLOW_HEX));8 //2559 ?>

 

 PHP技术交流群 170855791

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.