使用file_get_contents的第五个参数:
$s = file_get_contents('file', false, null, 0, 200);
这仅适用于 256 个字符集,并且不能正常适用于多字节字符,因为 PHP does not offer native Unicode support,很遗憾。
Unicode
为了读取特定数量的 Unicode 字符,您需要使用 PHP 扩展实现自己的函数,例如 intl 和 mbstring。例如,接受最大 UTF-8 字符数的fread 版本可以实现如下:
function utf8_fread($handle, $length = null) {
if ($length > 0) {
$string = fread($handle, $length * 4);
return $string ? mb_substr($string, 0, $length) : false;
}
return fread($handle);
}
如果$length 为正数,则函数读取该字符数的 UTF-8 字符串可以占用的最大字节数(一个 UTF-8 字符表示为 1 到 4 个 8 位字节),并且使用mb_substr 提取第一个$length 多字节字符。否则,该函数将读取整个文件。
file_get_contents 的 UTF-8 版本可以用类似的方式实现:
function utf8_file_get_contents(...$args) {
if (!empty($args[4])) {
$maxlen = $args[4];
$args[4] *= 4;
$string = call_user_func_array('file_get_contents', $args);
return $string ? mb_substr($string, 0, $maxlen) : false;
}
return call_user_func_array('file_get_contents', $args);
}