comparing strings in PHP with the == operator
来源:互联网 发布:格式工厂 mac破解版 编辑:程序博客网 时间:2024/05/20 05:25
最近在Greg Beaver's的blog上发表的一篇新文章 comparing strings in PHP with the == operator 中提及了PHP的 == 运算符在对字符串进行比较时值得注意的问题。
在某些情况下,PHP会把类数值数据(如含有数字的字符串等)转换成数值处理,== 运算符就是其中之一。在使用 == 运算符对两个字符串进行松散比较时,PHP会把类数值的字符串转换为数值进行比较,下面的实验证实了这个结论:
以上代码输出结果为:
<?php
var_dump('01' == 1);
?>
bool(true)
所以,在使用对字符串进行比较时,建议使用 === 运算符对字符串进行严格的检查,或使用strcmp()等函数,从而避免可能产生的问题。PHP手册中的《PHP 类型比较表》对此也有详细说明。
除此之外,常用的in_array()函数也存在弱类型的问题,见如下代码:<?php
var_dump(in_array('01', array('1')));
?>
以上代码输出结果为:
bool(true)
相信用过该函数进行安全性检查的PHP编程人员都知道这会产生怎么样的安全问题了吧?幸好in_array()函数为我们提供了第三个参数,把它设为 true 就可以打开in_array()函数的强制类型检查机制,如下代码所示:<?php
输出结果为:
var_dump(in_array('01', array('1'), true));
?>
bool(false)
由于PHP是一种弱类型的语言,也就是说数据类型这个概念在PHP中被弱化。因而如果在编程时过分忽略数据类型(也是大部份PHP程序员的通病),会产生一些问题,甚至导致安全漏洞。最后,还是那句说得很烦很烦的话,对外来数据进行严格检查和过滤。
ps:超过16位长度的字符串 用==比较 只要之前的16位相等 之后的数不相等 也会返回TRUE
so找到
- comparing strings in PHP with the == operator
- Comparing Strings
- Comparing Strings
- some software in Ubuntu comparing with Windows
- qmake "The *= operator"
- The in operator
- Comparing strings (C)
- A. Comparing Strings
- about “+=” operator in Java
- Comparing the Timer Classes in the .NET Framewo...
- Comparing the Timer Classes in the .NET Framework Class Library
- Polymorphism in Perl comparing with JAVA and C++
- The "tr///" operator in Perl
- Using UTF-8 as the internal representation for strings in C and C++ with Visual Studio
- Learning Perl: 8.4. The Binding Operator, =~
- the operator of file in web
- The Safe Navigation Operator (&.) in Ruby
- Java源码-字符串大小比较(Comparing Strings)
- 我看不懂
- xml 数据类型列的索引
- 为什么写博
- 我被XML“转义"折腾了一番
- VB复制文件夹的方法(非FSO)
- comparing strings in PHP with the == operator
- VC6.0 debug和release的区别及如何设置
- 一个直观但难的问题
- 关于键保留表(key-preserved table)
- The Django Book中文翻译版【第二版】
- VC6.0配置DirectShow开发环境
- 终于完成我的小程序了,感言一下
- 探寻 ibatis 1.3 批处理
- 关于mysql 的order by rand()