tags:

views:

1307

answers:

4

Is there a way in PHP to compile a regular expression, so that it can then be compared to multiple strings without repeating the compilation process? Other major languages can do this -- Java, C#, Python, Javascript, etc.

+2  A: 

I'm not positive that you can. If you check out Mastering Regular Expressions, some PHP specific optimization techniques are discussed in Chapter10: PHP. Specifically the use of the S pattern modifier to cause the regex engine to "Study" the regular expression before it applies it. Depending on your pattern and your text, this could give you some speed improvements.

Edit: you can take a peek at the contents of the book using books.google.com.

EBGreen
Every developer who use regex should read this book !!All the techniques you need to be efficient are in this book.
Arno
+2  A: 

preg regexes can use the uppercase S (study) modifier, which is probably the thing you're looking for.

http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php

S

When a pattern is going to be used several times, it is worth spending more time analyzing it in order to speed up the time taken for matching. If this modifier is set, then this extra analysis is performed. At present, studying a pattern is useful only for non-anchored patterns that do not have a single fixed starting character.

Imran
The answer to the OP's question is that there's no need to pre-compile regexes in PHP because, as 1stvamp noted, compiled regexes are cached automatically. The 'S' modifier is a separate issue.
Alan Moore
+7  A: 

The Perl-Compatible Regular Expressions library may have already be optimized for your use case without providing a Regex class like other languages do:

This extension maintains a global per-thread cache of compiled regular expressions (up to 4096).

PCRE Introduction

This is how the study modifier which Imran described can store the compiled expression between calls.

Pat Leahy
+1  A: 

As another commenter has already said, PCRE regexes are already compiled without your having to specifically reference them as such, PCRE keeps an internal hash indexed by the original string you provided.

1stvamp