为什么PHP strlen()返回负长度? [英] Why does PHP strlen() return negative length?

查看:84
本文介绍了为什么PHP strlen()返回负长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

strlen($ str) 使用 创建的巨大字符串返回负值, code> str_repeat

strlen($str) is returning negative values for a "huge string" that is created using str_repeat:

<?php

error_reporting(E_STRICT|E_ALL);
echo phpversion(); // 5.3.26
echo PHP_INT_MAX; // 9223372036854775807
ini_set('memory_limit', '-1');
ini_set('max_execution_time', 0);

$gb = 1024 * 1024 * 1024;
$str = str_repeat('a', 2 * $gb);
echo strlen($str); // gives int(-2147483648)
echo $str[0]; // Notice: Uninitialized string offset: 0

$str2 = str_repeat('a', 4 * $gb);
echo strlen($str2); // gives int(0)

$str3 = str_repeat('a', 123 + 4 * $gb);
echo strlen($str3); // gives int(123)

$str4 = str_repeat('a', 6 * $gb); // starts to wrap again...
echo strlen($str4); // gives int(-2147483648)
echo $str4[0]; // Notice: Uninitialized string offset: 0

$str5 = str_repeat('a', 123 + 8 * $gb);
echo strlen($str5); // gives int(123)

?>

是否定义了此行为?

或这是PHP错误吗?

推荐答案


string 可以大到2GB。

string can be as large as 2GB.

它实际上是(2GB - 1)。这在我的x64框上工作正常:

It looks like it is in fact (2GB - 1). This works fine on my x64 box:

$str = str_repeat('a', 2 * 1024 * 1024 * 1024 -1);
echo $str[0];

...这个休息时间:

... while this breaks:

$str = str_repeat('a', 2 * 1024 * 1024 * 1024);
echo $str[0];

您正在做的只是简单地未定义,手册应该被更正。我也会期待一个警告。

What you are doing is simply undefined, and the manual should be corrected. I would have expected a warning too.

有趣的是,这会引发致命错误:

Interestingly, this raises a fatal error:

$str = str_repeat('a', 2 * 1024 * 1024 * 1024 -2); // 2GB - 2 bytes
$str .= 'b'; // ok
$str .= 'c'; // PHP Fatal error:  String size overflow


更新:

错误报告已经参加。 php.net上的文档已经修复,现在写入最大2147483647个字节。

The bug report has been attended to. Documentation on php.net has been fixed and now writes "2147483647 bytes maximum".

这篇关于为什么PHP strlen()返回负长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆