Home >Backend Development >PHP Tutorial >How to Convert ereg Regular Expressions to preg in PHP?

How to Convert ereg Regular Expressions to preg in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-12-20 15:02:14187browse

How to Convert ereg Regular Expressions to preg in PHP?

Conversion from Ereg to Preg in PHP

In PHP, POSIX regular expressions (ereg) have been deprecated since version 5.3.0. To facilitate the transition, it's essential to understand how to convert old ereg expressions to PCRE (Perl Compatible Regular Expressions) (preg).

Syntax Differences

The primary syntax difference is the addition of delimiters in preg. For instance, the following ereg expression:

eregi('^hello world');

should be converted to a preg_match expression like this:

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

The delimiters can be various non-alphanumeric characters, with common choices being ~, /, and #.

Matching Brackets

Additionally, you can use matching brackets as delimiters:

preg_match('[^hello]', $str);
preg_match('(^hello)', $str);
preg_match('{^hello}', $str);

Escaping Delimiters

If your delimiter appears in the regular expression, escape it using a backslash:

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

To escape all delimiters and reserved characters, use preg_quote:

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

Modifiers

PCRE supports modifiers for various features. For instance, the case-insensitive modifier i replaces the eregi function:

eregi('^hello', 'HELLO');
preg_match('/^hello/i', 'HELLO');

Example Conversion

In your provided example, a regular expression is not necessary. Instead, you can use the following PHP function:

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

The above is the detailed content of How to Convert ereg Regular Expressions to preg in PHP?. 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