PHP Velho Oeste 2024

POSIX 正規表現との違い

PHP 5.3.0 以降、POSIX 正規表現 拡張モジュールは非推奨となりました。POSIX の正規表現と PCRE の正規表現にはさまざまな違いがあります。 このページでは、PCRE への移行の際に知っておくべきもっとも重要な違いをまとめます。

  1. PCRE 関数では、パターンを デリミタ で囲まなければなりません。
  2. POSIX とは異なり、PCRE 拡張モジュールには大文字小文字を区別しないマッチング専用の関数がありません。 同等の機能は、i (PCRE_CASELESS) パターン修飾子 でサポートしています。それ以外にもパターン修飾子がいくつかあり、 マッチングの振る舞いを変えることができます。
  3. POSIX 関数は、いちばん左側にある最も長くマッチするパターンを探します。 しかし PCRE は、マッチするパターンが最初に見つかった時点で処理を終えます。 マッチするパターンがまったくない文字列の場合は何も相違はありませんが、 マッチするパターンがある場合は結果や処理速度に大きな影響が出る可能性があります。 この違いを説明するために、Jeffrey Friedl の "Mastering Regular Expressions (「詳説 正規表現」)" にある以下の例を考えてみましょう。 PCRE でパターン one(self)?(selfsufficient)? を文字列 oneselfsufficient に適用すると oneself にマッチしますが、 POSIX の場合は文字列全体 oneselfsufficient にマッチします。 どちらの結果も元の文字列にマッチしますが、POSIX の場合はもっとも長いものを結果とするのです。
  4. POSIX における "文字クラス" の定義は PCRE とは異なります。 シンプルな角括弧を使って明示的な文字にマッチさせるというのが PCRE の 文字クラス ですが、POSIX の照合順序や文字クラスや等価文字には対応していません。 最初と最後が :. あるいは = で囲まれている文字クラスを PCRE で使うと、これらのサポートしていない機能を使うとして、コンパイルエラーが発生します。

関数の置き換え
POSIX PCRE
ereg_replace() preg_replace()
ereg() preg_match()
eregi_replace() preg_replace()
eregi() preg_match()
split() preg_split()
spliti() preg_split()
sql_regcase() No equivalent

add a note add a note

User Contributed Notes 2 notes

up
1
cdragon at dracoventions dot com
10 years ago
In regards to the previous comment that says "there are several other differences including different meaning for the symbols  ( [ different rules for which symbols need escaping", as far as I can tell from reading
http://www.tin.org/bin/man.cgi?section=7&topic=regex
there are absolutely no "other differences" except in what the man page calls "Obsolete  ("basic'')  regular  expressions".  However, PHP doesn't appear to use the obsolete form of expressions in its POSIX functions.

PCRE even supports all of the POSIX named character classes such as [:space:].
up
0
jasen at treshna dot com
12 years ago
there are several other differences

including different meaning for the symbols  ( [
different rules for which symbols need escaping (they can't be the same as both standard posix and extended posix)

you should read the full documentation for PCRE before chaging any posix regex to use pcre.
To Top