Home >Backend Development >PHP Tutorial >How Do I Migrate My PHP Code from `ereg` to `preg` Regular Expressions?

How Do I Migrate My PHP Code from `ereg` to `preg` Regular Expressions?

Barbara Streisand
Barbara StreisandOriginal
2024-12-26 11:38:10264browse

How Do I Migrate My PHP Code from `ereg` to `preg` Regular Expressions?

Migrating from EReg to PREG in PHP

Since PHP 5.3.0, POSIX regular expressions (ereg) have been deprecated, necessitating the adoption of Perl Compatible Regular Expressions (preg). This transition requires modifications to existing ereg expressions for compatibility with preg_match.

Syntax Differences

The key syntactic change involves adding delimiters to the expressions. Unlike ereg, preg requires delimiters before and after the regular expression. Delimiters can be characters like ~, /, or #, or even matching brackets (e.g., [], (), {}).

preg_match('/^hello/', $str); // Using '/' as a delimiter
preg_match('[^hello]', $str); // Using square brackets as a delimiter

Escaping Delimiters

If the chosen delimiter appears within the regular expression, escape it using a backslash ().

preg_match('/^\/hello/', $str);

Using preg_quote

For comprehensive escaping of all delimiters and reserved characters, use preg_quote:

$expr = preg_quote('/hello', '/');
preg_match('/^'.$expr.'/', $str);

Case-Insensitive Matching

To perform case-insensitive matching, utilize the i modifier:

preg_match('/^hello/i', $str);

Converting the Given Example

The provided example, eregi('^hello world'), should not be converted to preg_match since it can be simplified using the stripos function:

stripos($str, 'hello world') === 0

The above is the detailed content of How Do I Migrate My PHP Code from `ereg` to `preg` Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn