28.19. Don't Use Regular Expressions Unless You Must

PHP features a very large library of string functions, some of which are extremely powerful. However, in many situations two or more functions can be used to perform the same task, but with great differences in performance.

Perhaps the most commonly overused functions are ereg_replace and preg_replace. These regular-expression-based pattern-replacing functions are often used even when the replacement pattern is completely static and there's no need for compiling a complex regular expression. For instance,

$str = ereg_replace("sheep", "lamb", "Mary had a little sheep");

can be up to 10 times slower than the equivalent

$str = str_replace("Mary had a little sheep", "sheep", "lamb");

Use regular ...

Get Core PHP Programming, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.