Alex Rivera | Logout

PHP ereg vs. preg

Asked 2009-09-01T09:57:52.333
39

I have noticed in the PHP regex library there is a choice between ereg and preg. What is the difference? Is one faster than the other and if so, why isn't the slower one deprecated?

Are there any situations where it is better to use one over the other?

Edit
Report

1 Answer

5

There is much discussion about which is faster and better.

If you plan on someday advancing to PHP6 your decision is made. Otherwise:

The general consensus is that PCRE is the better all around solution, but if you have a specific page with a lot of traffic, and you don't need PHP6 it may be worth some testing. For example, from the PHP manual comments:

Deprecating POSIX regex in PHP for Perl searching is like substituting wooden boards and brick for a house with pre-fabricated rooms and walls. Sure, you may be able to mix and match some of the parts but it's a lot easier to modify with all the pieces laid out in front of you.

PCRE faster than POSIX RE? Not always. In a recent search-engine project here at Cynergi, I had a simple loop with a few cute ereg_replace() functions that took 3min to process data. I changed that 10-line loop into a 100-line hand-written code for replacement and the loop now took 10s to process the same data! This opened my eye to what can IN SOME CASES be very slow regular expressions. Lately I decided to look into Perl-compatible regular expressions (PCRE). Most pages claim PCRE are faster than POSIX, but a few claim otherwise. I decided on bechmarks of my own. My first few tests confirmed PCRE to be faster, but... the results were slightly different than others were getting, so I decided to benchmark every case of RE usage I had on a 8000-line secure (and fast) Webmail project here at Cynergi to check it out. The results? Inconclusive! Sometimes PCRE are faster (sometimes by a factor greater than 100x faster!), but some other times POSIX RE are faster (by a factor of 2x). I still have to find a rule on when are one or the other faster. It's not only about search data size, amount of data matched, or "RE compilation time" which would show when you repeated the function often: one would

answered 2009-09-01T10:30:12.393

Your Answer