php filter(二)

Jun 23, 2016 pm 02:35 PM

Boolean验证 FILTER_VALIDATE_BOOLEAN

1 <?php2 3 /*** test for a boolean value ***/4 echo filter_var("true", FILTER_VALIDATE_BOOLEAN);5 //16 ?> 
Copy after login

上面的代码输出1,因为过滤器发现了一个有效的布尔值,下面列出了其它可以返回true的值
1
"1"
"yes"
"true"
"on"
TRUE
下列值将会返回false
0
"0"
"no"
"false"
"off"
""
NULL
FALSE
同时也支持下面的用法

1 <?php2 3 /*** a simple array ***/4 $array = array(1,2,3,4,5);5 6 /*** test for a boolean value ***/7 echo filter_var(in_array(3, $array), FILTER_VALIDATE_BOOLEAN) ? "TRUE" : "FALSE";8 //true9 ?>
Copy after login

在上面的代码中,先判断了in_array函数执行成功,返回了true,所以最后这段代码输出true
我们也可以传递一个数组,来判断数组中值的boolean类型

 1 <?php 2  3 /*** a multi dimensional array ***/ 4 $array = array(0,1,2,3,4, array(0,1,2,3,4)); 5  6 /*** create the list of values ***/ 7 $values = filter_var($array, FILTER_VALIDATE_BOOLEAN, FILTER_REQUIRE_ARRAY); 8  9 /*** dump the values ***/10 var_dump($values);11 12 ?>
Copy after login

上面代码输出如下:
array(6) {
[0]=> bool(false)
[1]=> bool(true)
[2]=> bool(false)
[3]=> bool(false)
[4]=> bool(false)
[5]=> array(5) {
[0]=> bool(false)
[1]=> bool(true)
[2]=> bool(false)
[3]=> bool(false)
[4]=> bool(false)
}
}

浮点型验证 FILTER_VALIDATE_FLOAT

 1 <?php 2  3 /*** an FLOAT value to check ***/ 4 $float = 22.42; 5  6 /*** validate with the FLOAT flag ***/ 7 if(filter_var($float, FILTER_VALIDATE_FLOAT) === false) 8 { 9     echo "$float is not valid!";10 }11 else12 {13     echo "$float is a valid floating point number";14 }15 ?> 
Copy after login

同其它验证一样,也可以对一个数组进行浮点型验证。与boolean验证类似,提供一个flgs FILTER_REQUIRE_ARRAY。

/*** an array of values ***/
$array = array(1.2,"1.7","", "-12345.678", "some text", "abcd4.2efgh", array());

/*** validate the array ***/
$validation_array = filter_var($array, FILTER_VALIDATE_FLOAT, FILTER_REQUIRE_ARRAY);

/*** dump the array of validated data ***/
var_dump($validation_array);

?>
上面的代码输出如下
array(7) {
[0]=> float(1.2)
[1]=> float(1.7)
[2]=> bool(false)
[3]=> float(-23234.123)
[4]=> bool(false)
[5]=> bool(false)
[6]=> array(0) { }
}
浮点型过滤器支持我们指定一个数字间的分隔符

 1 <?php 2  3 /*** an array of floats with seperators ***/ 4 $floats = array( 5 "1,234" => ",", 6 "1.234" => "..", 7 "1.2e3" => "," 8 ); 9 10 /*** validate the floats against the user defined decimal seperators ***/11 foreach ($floats as $float => $dec_sep)12 {13     $out = filter_var($float, FILTER_VALIDATE_FLOAT,     array("options"=>array("decimal" => $dec_sep)));14     /*** dump the results ***/15     var_dump($out);16 }17 ?>
Copy after login

在上面的代码中,$floats函数中第一个元素值为',',所以在判断1,234值时为其指定了分隔符为',',所以返回true
上面代码完整返回值
float(1.234)
Warning: filter_var() [function.filter-var]: decimal separator must be one char in /www/filter.php on line 13
bool(false)
bool(false)

验证URL FILTER_VALIDATE_URL
URL的验证是一项很困难的行为,由于URL的不确定性,它没有最大长度的限制,而且它的格式是多样化的,你可以通过阅读RFC 1738来了解有关URL的一些信息。之后你可以创建一个类来验证所有ipv4和ipv6的URL,以及一些其它URL的验证。你也可以简单的使用FILTER_VALIDATE_URL来验证URL。

 1 <?php 2  3 /*** a rfc compliant web address ***/ 4 $url = "http://www.phpro.org"; 5  6 /*** try to validate the URL ***/ 7 if(filter_var($url, FILTER_VALIDATE_URL) === FALSE) 8 { 9     /*** if there is no match ***/10     echo "Sorry, $url is not valid!";11 }12 else13 {14     /*** if we match the pattern ***/15     echo "The URL, $url is valid!<br />";16 }17 ?>
Copy after login

上面的例子中通过简单的if语句来判断给定的URL是否合法,但并不是所有的URL都是这样的格式。有时候URL可是能是一个IP地址,也可能在URL中传递了多个参数。下面提供了几个flags来帮助我们验证URL
FILTER_FLAG_SCHEME_REQUIRED - 要求 URL 是 RFC 兼容 URL。(比如:http://example)
FILTER_FLAG_HOST_REQUIRED - 要求 URL 包含主机名(http://www.example.com)
FILTER_FLAG_PATH_REQUIRED - 要求 URL 在主机名后存在路径(比如:eg.com/example1/)
FILTER_FLAG_QUERY_REQUIRED - 要求 URL 存在查询字符串(比如:"eg.php?age=37")

 1 <?php 2  3 /*** a non rfc compliant URL ***/ 4 $url = "index.php"; 5  6 /*** try to validate the URL ***/ 7 if(filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED) === FALSE) 8 { 9     /*** if there is no match ***/10    echo "Sorry, $url is not valid!";11 }12 else13 {14     /*** if the URL is valid ***/15     echo "The URL, $url is valid!";16 }17 ?>
Copy after login

可以发现,上面的代码没有通过验证

IP过滤器 FILTER_VALIDATE_IP
FILTER_VALIDATE_IP 过滤器把值作为 IP 进行验证。
Name: "validate_ip"
ID-number: 275
可能的标志:
FILTER_FLAG_IPV4 - 要求值是合法的 IPv4 IP(比如 255.255.255.255)
FILTER_FLAG_IPV6 - 要求值是合法的 IPv6 IP(比如 2001:0db8:85a3:08d3:1319:8a2e:0370:7334)
FILTER_FLAG_NO_PRIV_RANGE - 要求值是 RFC 指定的私域 IP (比如 192.168.0.1)
FILTER_FLAG_NO_RES_RANGE - 要求值不在保留的 IP 范围内。该标志接受 IPV4 和 IPV6 值。

Email过滤器FILTER_VALIDATE_EMAIL
FILTER_VALIDATE_EMAIL 过滤器把值作为电子邮件地址来验证。

 1 <?php 2 $email = "someone@exa mple.com"; 3  4 if(!filter_var($email, FILTER_VALIDATE_EMAIL)) 5  { 6      echo "E-mail is not valid"; 7  } 8 else 9  {10      echo "E-mail is valid";11  }12 ?>
Copy after login

自定义过滤器 FILTER_CALLBACK

FILTER_CALLBACK 过滤器使用用户自定义函数对值进行过滤。
这个过滤器为我们提供了对数据过滤的完全控制。
指定的函数必须存入名为 "options" 的关联数组中。

 1 <?php 2 function convertSpace($string) 3  { 4      return str_replace(" ", "_", $string); 5  } 6  7 $string = "Peter is a great guy!"; 8  9 echo filter_var($string, FILTER_CALLBACK,10 array("options"=>"convertSpace"));11 ?>
Copy after login

输出

Peter_is_a_great_guy!
Copy after login


PHP技术交流群 170855791

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

PHP Logging: Best Practices for PHP Log Analysis PHP Logging: Best Practices for PHP Log Analysis Mar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles