Php sample code for intercepting n characters starting at a certain position in the GBK document

Source: Internet
Author: User
Tags php sample code
The following is a small compilation of the n-character method for intercepting a GBK document by using php at a certain position. I think this is quite good. now I will share it with you and give you a reference. Let's take a look at the following small series to bring you a php method to intercept the GBK document at a certain position starting with n characters. I think this is quite good. now I will share it with you and give you a reference. Let's take a look at it with Xiaobian.

Cut. php:


#!/usr/bin/php
 = $file_size) exit;$fp = fopen(INPUT_FILE, 'rb');$point = 0; //current byte position$string = ''; while(ftell($fp) < $file_size) {  if($point >= $pos + $len) break;$byte = fread($fp, 1);   //php version >= 5.4  $char = unpack('C', $byte)[1];  if($char <= 0x7f) {    //single byte    if($point >= $pos) $string .= $byte;    $point += 1;    continue;  } else {    //double bytes    if($point >= $pos) {      $string .= $byte.fread($fp, 1);     } else {      fseek($fp, 1, SEEK_CUR);    }    $point += 1;    continue;  }  }fclose($fp);file_put_contents(OUTPUT_FILE, $string);?>

SOURCE file t.txt content:

Dkei20 Wang nnso

Test Command:

./cut.php 6 1

View results:

hexdump -C t.txt && hexdump -C a.txt

The above is a detailed description of the sample code for php to capture the n characters starting at a certain position in the GBK document. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.