antevenio/stream-regex-iterator

PHP 流中正则表达式匹配迭代器

0.0.4 2019-05-16 11:43 UTC

This package is auto-updated.

Last update: 2024-09-17 03:27:28 UTC


README

在可寻址文本流中查找正则表达式匹配,并将它们返回为迭代器内的结果。

描述

此迭代器是解决在不耗尽内存的情况下对大文件执行复杂多行正则表达式的解决方案。

迭代器将从流中读取数据块,并对每个数据块执行 preg_match_all()

迭代器将以确保不会因数据块而丢失任何可能的匹配项的方式读取数据块,即,可能的匹配项存在于数据块分割点之间。

迭代器将按 preg_match_all() 使用 PREG_SET_ORDER | PREG_OFFSET_CAPTURE 标志时的方式返回匹配项。

限制

指定的流必须是完全可寻址的(前后均可)。

指定的缓冲区大小必须能够存储正则表达式的可能最长完整匹配。

迭代器将需要大约两倍的指定缓冲区大小的内存。

要求

以下版本的 PHP 被支持。

  • PHP 5.6
  • PHP 7.0
  • PHP 7.1
  • PHP 7.2
  • PHP 7.3

安装

composer require antevenio/stream-regex-iterator

用法

$inputString = "line1\nline2\nline3\nline4\nline5\nstart\nline6\nline7\nend";

$stream = fopen("data://text/plain," . $inputString, "r");

$matches = new Antevenio\StreamRegexIterator\Iterator(
    "/^start.*?end$/sm",
    $stream,
    32
);

foreach ($matches as $match) {
    print_r($match);
}

将输出

Array
(
    [0] => Array
        (
            [0] => start
line6
line7
end
            [1] => 30
        )

)