Main Content

PHP - moving from ereg to preg for regular expressions

Archive - Originally posted on "The Horse's Mouth" - 2011-11-11 20:27:50 - Graham Ellis

If your PHP scripts use "ereg" functions for regular expression matching, you should be aware that as from PHP version 5.3 they have been deprecated, and in PHP 6.0 the plan is to remove them completely.

The regular expressions move from the POSIX standard to the Perl standard. The function names change. Delimiters are added to the regular expression in the preg functions, with modifiers supported. There's a simple example [here].

So
  if (eregi('[A-Z]{1,2}[0-9]{1,2} {0,}[0-9]{1}[A-Z]{2}',$code))
becomes
  if (preg_match('/[A-Z]{1,2}[0-9]{1,2} {0,}[0-9]{1}[A-Z]{2}/i',$code))

Here's a table showing the old ereg names and the preg functions which may replace them:

in old codeare replaced by
ereg and eregipreg_match or preg_match_all
ereg_replace and eregi_replacepreg_replace or preg_filter or preg_replace_callback
split and splitipreg_split
-preg_grep and preg_quote