CakeFest 2024: The Official CakePHP Conference

RegexIterator クラス

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

はじめに

このイテレータを使うと、別のイテレータを正規表現でフィルタリングすることができます。

クラス概要

class RegexIterator extends FilterIterator {
/* 定数 */
public const int USE_KEY;
public const int INVERT_MATCH;
public const int MATCH;
public const int GET_MATCH;
public const int ALL_MATCHES;
public const int SPLIT;
public const int REPLACE;
/* プロパティ */
public ?string $replacement = null;
/* メソッド */
public __construct(
    Iterator $iterator,
    string $pattern,
    int $mode = RegexIterator::MATCH,
    int $flags = 0,
    int $pregFlags = 0
)
public accept(): bool
public getFlags(): int
public getMode(): int
public getPregFlags(): int
public getRegex(): string
public setFlags(int $flags): void
public setMode(int $mode): void
public setPregFlags(int $pregFlags): void
/* 継承したメソッド */
}

定義済み定数

RegexIterator の操作モード

RegexIterator::ALL_MATCHES

現在のエントリにマッチするものをすべて返します (preg_match_all() を参照ください)。

RegexIterator::GET_MATCH

現在のエントリに最初にマッチしたものを返します (preg_match() を参照ください)。

RegexIterator::MATCH

現在のエントリに対するマッチ (フィルタ) のみを行います (preg_match() を参照ください)。

RegexIterator::REPLACE

現在のエントリを置換します (preg_replace() を参照ください。まだ完全には実装されていません)。

RegexIterator::SPLIT

現在のエントリで分割した値を返します (preg_split() を参照ください)。

RegexIterator のフラグ

RegexIterator::USE_KEY

特別なフラグ: エントリの値ではなく、キーにマッチさせます。

RegexIterator::INVERT_MATCH

RegexIterator::accept() の戻り値を反転させます。

プロパティ

replacement

目次

add a note

User Contributed Notes 2 notes

up
33
jinmoku at hotmail dot com
13 years ago
An exemple :

<?php
$a
= new ArrayIterator(array('test1', 'test2', 'test3'));
$i = new RegexIterator($a, '/^(test)(\d+)/', RegexIterator::REPLACE);
$i->replacement = '$2:$1';

print_r(iterator_to_array($i));
/*
Array
(
[0] => 1:test
[1] => 2:test
[2] => 3:test
)
*/
?>
up
1
chris dot snyder at totara dot com
1 year ago
In case the difference between modes RegexIterator::MATCH and RegexIterator::GET_MATCH is not immediately clear:

MATCH will only return one value per matched element, as a string.

GET_MATCH will return as many values, per matched element, as there are sub-patterns. If there are sub-patterns, each iteration returns an indexed array with the full pattern match at 0 and each of the sub-pattern matches as another element.

If there are no sub-patterns, the behaviour of GET_MATCH is the same as MATCH.
To Top