13.1. Switching From ereg to preg

Problem

You want to convert from using ereg functions to preg functions.

Solution

First, you have to add delimiters to your patterns:

preg_match('/pattern/', 'string')

For eregi( ) case-insensitive matching, use the /i modifier instead:

preg_match('/pattern/i', 'string');

When using integers instead of strings as patterns or replacement values, convert the number to hexadecimal and specify it using an escape sequence:

$hex = dechex($number);
preg_match("/\x$hex/", 'string');

Discussion

There are a few major differences between ereg and preg. First, when you use preg functions, the pattern isn’t just the string pattern; it also needs delimiters, as in Perl, so it’s /pattern/ instead.[10] So:

ereg('pattern', 'string');

becomes:

preg_match('/pattern/', 'string');

When choosing your pattern delimiters, don’t put your delimiter character inside the regular-expression pattern, or you’ll close the pattern early. If you can’t find a way to avoid this problem, you need to escape any instances of your delimiters using the backslash. Instead of doing this by hand, call addcslashes( ) .

For example, if you use / as your delimiter:

$ereg_pattern = '<b>.+</b>';
$preg_pattern = addcslashes($ereg_pattern, '/');

The value of $preg_pattern is now <b>.+<\/b>.

The preg functions don’t have a parallel series of case-insensitive functions. They have a case-insensitive modifier instead. To convert, change:

eregi('pattern', 'string');

to:

preg_match('/pattern/i', 'string'); ...

Get PHP Cookbook 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.