gpt4 book ai didi

php - 什么时候使用 PHP strtolower() 函数是安全的?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:50:16 30 4
gpt4 key购买 nike

PHP strtolower() 函数应该将字符串转换为小写。但是,它说 in the PHP Manual (强调):

Returns string with all alphabetic characters converted to lowercase.

Note that 'alphabetic' is determined by the current locale. This means that in i.e. the default "C" locale, characters such as umlaut-A (Ä) will not be converted.

手册在这里没有提及编码,但众所周知 strtolower() 会损坏 UTF-8 字符串,您应该使用 mb_strtolower() 代替.

我正在寻找解决方案,以应对 mbstring 扩展不可用的情况,并且想知道何时可以安全地使用 strtolower()

感谢评论这个问题的人给我的指示,PHP 源代码的相关部分似乎是调用 ctype.h 中的 tolower() 函数 库。 library documentation说(强调):

If the argument of tolower() represents an uppercase letter, and there exists a corresponding lowercase letter (as defined by character type information in the program locale category LC_CTYPE ), the result shall be the corresponding lowercase letter.

根据我的测试,在带有 set_locale( LC_CTYPE, 'C' ); 的 PHP 中,诸如 Ä(编码为 ISO-8859-1)的字符保持不变.但在其他一些语言环境中,该函数返回小写的 ä(同样,在 ISO-8859-1 中)。无论如何,将语言环境更改为使用 UTF-8 字符集的语言环境不会使 PHP strtolower() 可以处理 UTF-8 字符 Ä.

考虑到越来越多的 I18N 相关问题和多语言环境,此信息可能至关重要。许多应用程序依赖于 strtolower() 进行简单的不区分大小写的检查。考虑:

$_POST['username'] = 'Michèlle';
if ( strtolower( $_POST['username'] ) == $database['username'] ) ...

现在,根据编码、语言环境和可能的其他一些变量,上面的代码将在某些环境中工作,但在其他环境中不工作。

问题是:鉴于 PHP strtolower() 函数使用 ctype.h 库的 tolower 函数,这取决于“程序locale category”,什么时候可以安全地依赖这个函数?在以下情况下可以指望该行为吗?

  1. 字符串是ASCII
  2. 字符串以 ISO-8859-1 编码
  3. 该字符串使用其他一些具有相应区域设置的编码进行编码。

(编辑:问题已于 2013 年 11 月 26 日完全改写。)

最佳答案

strtolower() PHP 函数在其实现中确实使用了 tolower() C 函数,该函数对传递的字符串参数的每个字节(八位字节)进行操作。

这就是为什么 setlocale(LC_CTYPE, 'C' ); 不会破坏 UTF-8 编码字符串的原因,因为它不会改变大于 127 的字节。也就是说,它只会改变大小写US-ASCII 字符 A-Z。

C”区域设置是默认设置的,您不需要使用 setlocale() 显式设置它,只有在应用程序的其他部分已经设置它的情况下到不同的值。

这也解释了为什么将 LC_CTYPE 设置为像“de_DE.UTF-8”这样的 UTF8 语言环境不会将“Ä”转换为“ä":该字母用两个字节 0xC3 0x84 编码,其中两个字节都作为单个字符(八位字节)传递给 tolower() C 函数 - 因此它们没有变化对于单个字节,UTF-8 到较低的处理只能处理 < 128 的字符,这又是有效的 A-Z。这实际上类似于 C 语言环境。

因此将 LC_CTYPE 设置为“C”可防止破坏 strtolower() 使用的 UTF-8 字符串。

关于php - 什么时候使用 PHP strtolower() 函数是安全的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20101371/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com