michaelgarrez / text-file
文本文件操作
v0.0.1
2016-03-05 13:43 UTC
Requires
- symfony/filesystem: ^3.0
Requires (Dev)
- phpunit/phpunit: ^5.2
This package is auto-updated.
Last update: 2024-09-12 03:52:27 UTC
README
介绍
这个库通过提供多种方法来读取、解析和写入文本文件,简化了PHP中文本文件的操作。
安装
composer install michaelgarrez/text-file
基础
打开文件
<?php $textFile = new TextFile('text_file.txt');
如果存在 text_file.txt 文件,则将其打开,否则创建该文件。
遍历
WalkerInterface
所有遍历相关操作都通过 WalkerInterface 的实例(默认为 SimpleWalker)进行。所有以下方法都接受一个可选的实现了 WalkerInterface 的类来覆盖 SimpleWalker。
用法
<?php $textFile = new TextFile('text_file.txt'); // Move to a specific line $textFile->goToLine(5); // This does not return the line content (See Reading). // Count lines $count = $textFile->countLines(5); // Move before a specific character $textFile->goBeforeCharacter(5); // This does not return the line content (See Reading).
读取
ReadingInterface
所有读取相关操作都通过一个实现了 ReaderInterface 的实例(默认为 ReaderWalker)进行。
ReaderInterface 实现需要一个 WalkerInterface 实现来工作。
所有以下方法接受两个可选参数
- 实现了 ReaderInterface 的类来覆盖 SimpleReader。
- 实现了 WalkerInterface 的类来覆盖 SimpleWalker。
用法
所有这些方法将指针重置到其上一个位置。换句话说,它 不会移动内部指针。
<?php $textFile = new TextFile('text_file.txt'); // Getting lines range $iterator = $textFile->getLinesRange(0, 5); // Returns an Iterator containing line content from a line to another $textFile->goToLine(4); // Getting current line content $content = $textFile->getCurrentLineContent(); // Returns content of line 4 // Getting next line content $content = $textFile->getNextLineContent(); // Returns content of line 5 // Getting previous line content $content = $textFile->getPreviousLineContent(); // Returns content of line 3 // Getting specific line content $content = $textFile->getLineContent(6); // Returns content of line 6 // Getting next character content $character = $textFile->getNextCharacterContent(); // Returns next character after pointer position // Getting previous character content $character = $textFile->getNextCharacterContent(); // Returns previous character after pointer position // Getting specific character content $character = $textFile->getCharacterContent(7); // Returns 7 character from beginning of file
写入
WritingInterface
所有遍历相关操作都通过一个实现了 WriterInterface 的实例(默认为 PrependingWriter,写入时不会删除内容)进行。
另一个可用的写者是 ErasingWriter,写入时会删除内容(与 Insert 键盘行为相同)。
所有以下方法都接受一个可选的实现了 WriterInterface 的类来覆盖 PrependingWriter。
用法
<?php $textFile = new TextFile('text_file.txt'); // Write without erasing without return line break at the end $textFile->write('test'); // Write without erasing with return line break at the end $textFile->write('test', true); // Write with erasing without return line break at the end $textFile->write('test', false, TextFile\Writer::class); // Write with erasing with return line break at the end $textFile->write('test', true, TextFile\Writer::class);