[英]How to get x amount of characters from text file using php?
I'm trying to get about 200 letters/chars (including spaces) from a external text file. 我正在尝试从外部文本文件中获取大约200个字母/字符(包括空格)。 I've got the code to display the text i'll include that but to get certain letters i've got no idea. 我有代码来显示要包含的文本,但是要获得某些字母我不知道。 Once again i'm not talking about line's i really mean letters. 我再一次不是在说线,我的意思是字母。
<?php
$file = "Nieuws/NieuwsTest.txt";
echo file_get_contents($file) . '<br /><br />';
?>
Use the fifth parameter of file_get_contents
: 使用file_get_contents
的第五个参数:
$s = file_get_contents('file', false, null, 0, 200);
This will work only with 256-character set, and will not work correctly with multi-byte characters, since PHP does not offer native Unicode support , unfortunately. 不幸的是,这仅适用于256个字符集,并且不适用于多字节字符,因为PHP 不提供本机Unicode支持 。
In order to read specific number of Unicode characters, you will need to implement your own function using PHP extensions such as intl and mbstring . 为了读取特定数量的Unicode字符,您将需要使用诸如intl和mbstring之类的PHP扩展来实现自己的功能。 For example, a version of fread
accepting the maximum number of UTF-8 characters can be implemented as follows: 例如,接受最大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);
}
If $length
is positive, the function reads the maximum number of bytes that a UTF-8 string of that number of characters can take (a UTF-8 character is represented as 1 to 4 8-bit bytes), and extracts the first $length
multi-byte characters using mb_substr
. 如果$length
为正数,则该函数读取该数目的字符的UTF-8字符串可以占用的最大字节数(UTF-8字符表示为1至4个8位字节),并提取第一个$length
为mb_substr
多字节字符。 Otherwise, the function reads the entire file. 否则,该函数将读取整个文件。
A UTF-8 version of file_get_contents
can be implemented in similar manner: 可以通过类似的方式实现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);
}
You should use substr() functions. 您应该使用substr()函数。
But i recommend you to use the multy byte safe mb_substr() . 但我建议您使用多字节安全mb_substr() 。
$text = mb_substr( file_get_contents($file), 200 ) . '<br /><br />';
With substr you will get trouble if there is some accents etc. Thoses problems will not happen with mb_substr() 使用substr时,如果有一些重音等,您会遇到麻烦。mb_substr()不会发生这些问题
use this: 用这个:
<?php
$file = "Nieuws/NieuwsTest.txt";
echo substr( file_get_contents($file), 0, 200 ) . '<br /><br />';
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.