CakeFest 2024: The Official CakePHP Conference

デリミタ

PCRE 関数を使うときには、パターンを delimiters で囲まなければなりません。 英数字、バックスラッシュ、空白文字以外の任意の文字をデリミタとして使うことができます。 有効なデリミタの前に空白文字を付けても、黙って無視されます。

デリミタとしてよく使われる文字は、スラッシュ (/)、 ハッシュ記号 (#) およびチルダ (~) です。 次に示す例は、どれも正しいデリミタです。

/foo bar/
#^[^0-9]$#
+php+
%[a-zA-Z0-9_-]%

角括弧形式のデリミタを使うこともできます。 これは、開き角括弧と閉じ角括弧がそれぞれ開始デリミタ、終了デリミタを表す形式です。 (){}[] そして <> はどれも、角括弧形式のデリミタとして有効です。

(this [is] a (pattern))
{this [is] a (pattern)}
[this [is] a (pattern)]
<this [is] a (pattern)>
角括弧形式のデリミタを使う場合は、パターン内でメタ文字を使うときのエスケープは不要です。 しかし、他のデリミタと同様、(メタ文字としてではなく) リテラルとして扱う場合は、 エスケープする必要があります。

パターンの中でデリミタ文字をマッチさせたい場合は、バックスラッシュでエスケープしなければなりません。 パターン内でデリミタが頻繁にあらわれる場合は、 デリミタを別の文字に変更したほうが読みやすくなります。

/http:\/\//
#http://#
preg_quote() 関数を使うと、パターンに使う文字列をエスケープすることができます。 オプションの二番目のパラメータで、エスケープするデリミタを指定します。

終了デリミタの後に パターン修飾子 を付加することもできます。次の例は、大文字小文字を区別しないマッチを行うものです。

#[a-z]#i

add a note

User Contributed Notes 3 notes

up
36
Pedro Gimeno
9 years ago
Note that bracket style opening and closing delimiters aren't a 100% problem-free solution, as they need to be escaped when they aren't in matching pairs within the expression. That mismatch can happen when they appear inside character classes [...], as most meta-characters lose their special meaning. Consider these examples:

<?php
preg_match
('{[{]}', ''); // Warning: preg_match(): No ending matching delimiter '}'
preg_match('{[}]}', ''); // Warning: preg_match(): Unknown modifier ']'
preg_match('{[}{]}', ''); // Warning: preg_match(): Unknown modifier ']'
?>

Escaping them solves it:

<?php
preg_match
('{[\{]}', ''); // OK
preg_match('{[}]}', ''); // OK
preg_match('{[\}\{]}', ''); // OK
?>
up
12
Munin
8 years ago
preg_match('{[}]}', ''); // Warning: preg_match(): Unknown modifier ']'

preg_match('{[\}]}', ''); // OK
up
4
Revo
5 years ago
Note that angle brackets `<>` shouldn't be used as delimiters whenever you will have to invoke advanced clusters like atomic groups or lookbehinds because their including angle bracket doesn't come in pair and escaping doesn't help either.
To Top