首页 > 开发 > PHP > 正文

php 截取GBK文档某个位置开始的n个字符方法

2024-05-04 22:01:14
字体:
来源:转载
供稿:网友

cut.php:

  1. #!/usr/bin/php 
  2. <?php 
  3. define('INPUT_FILE','t.txt'); 
  4. define('OUTPUT_FILE','a.txt'); 
  5. $pos= max(intval($argv[1]), 0); 
  6. $len= max(intval($argv[2]), 0); 
  7. $file_size=filesize(INPUT_FILE); 
  8. if($pos>=$file_size)exit
  9. $fp=<a href="/tags.php/fopen/" target="_blank">fopen</a>(INPUT_FILE,'rb'); 
  10. $point= 0;//current byte position 
  11. $string='' 
  12. while(ftell($fp) <$file_size) { 
  13.   if($point>=$pos+$len)break;$byte=fread($fp, 1); 
  14.   //php version >= 5.4 
  15.   $char= unpack('C',$byte)[1]; 
  16.   if($char<= 0x7f) { 
  17.     //single byte 
  18.     if($point>=$pos)$string.=$byte
  19.     $point+= 1; 
  20.     continue
  21.   }else
  22.     //double bytes 
  23.     if($point>=$pos) { 
  24.       $string.=$byte.fread($fp, 1); 
  25.     }else
  26.       fseek($fp, 1, SEEK_CUR); 
  27.     } //Vevb.com 
  28.     $point+= 1; 
  29.     continue
  30.   }  
  31. fclose($fp); 
  32. file_put_contents(OUTPUT_FILE,$string); 
  33. ?> 

源文件t.txt内容:dkei20王nnso

测试命令:./cut.php 6 1

查看结果:hexdump -C t.txt && hexdump -C a.txt

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表