简体   繁体   中英

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. 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 :

$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.

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 . For example, a version of fread accepting the maximum number of UTF-8 characters can be implemented as follows:

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 . Otherwise, the function reads the entire file.

A UTF-8 version of file_get_contents can be implemented in similar manner:

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.

But i recommend you to use the multy byte safe 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()

use this:

<?php
    $file = "Nieuws/NieuwsTest.txt";
    echo substr( file_get_contents($file), 0, 200 ) . '<br /><br />';
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM