Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

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'); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata